lua - 如何忽略Luacheck警告?

标签 lua luacheck

Luacheck linter当 if 语句分支不包含任何语句时会产生警告。例如,如果我有一个名为 test.lua 的文件,其中包含以下代码

local function f(x)
    if x == "hello" then
        -- nothing to do
    elseif x == "world" then
        print(17)
    else
        error("bad value for x")
    end
end

f("world")

然后运行luacheck test.lua将产生以下诊断

Checking test.lua                                 1 warning

    test.lua:2:21: empty if branch

Total: 1 warning / 0 errors in 1 file

有办法解决这个警告吗?据我所知,没有配置选项可以禁用它,并且尝试使用分号来执行某些空语句也不会消除警告(事实上,它只会添加有关空语句的附加警告):

if x == "hello" then
    ;
elseif ...

目前我能想到的唯一解决方法是创建一个额外的 if 语句层,我认为这比原始版本不太清晰。

if x ~= "hello" then
    if x == "world" then
        print(17)
    else
        error("impossible")
    end
end

最佳答案

luacheck test.lua --ignore 542

请引用Luacheck文档。 Command Line Interface

CLI options --ignore, --enable and --only and corresponding config options allow filtering warnings using pattern matching on warning codes,...

List of Warnings

Code | Description

542 | An empty if branch.

或者,也可以通过在 .luacheckrc Configuration File 中设置 ignore 选项来禁用警告。 :

ignore = {"542"}
<小时/>

就我个人而言,我不喜欢忽略警告。我更愿意解决他们的问题。

所以我对您的特定问题的解决方案是简单地重新排列条件。这不需要像您提出的替代方案那样额外的 if 层。

local function f(x)
    if x == "world" then
        print(17)
    elseif x ~= "hello" then
        error("bad value for x")
    end
end

f("world")

关于lua - 如何忽略Luacheck警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49158143/

相关文章:

lua - 获取用于在 Lua 中创建协程/线程的函数

lua - Lua如何通过索引获取值

lua - __index 元方法中的无限递归

c# - 使用套接字将数据从C#应用程序发送到Lua应用程序

lua - 如何在 luacheck 中将警告设为错误?

c++ - 从 C++ 调用 Lua 函数不使用 2 个定义的函数