如何忽略Luacheck警告?

hug*_*omg 4 lua luacheck

当if语句分支不包含任何语句时,Luacheck linter会发出警告.例如,如果我有一个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")
Run Code Online (Sandbox Code Playgroud)

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

Checking test.lua                                 1 warning

    test.lua:2:21: empty if branch

Total: 1 warning / 0 errors in 1 file
Run Code Online (Sandbox Code Playgroud)

有办法解决这个警告吗?据我所知,没有配置选项来禁用它,并尝试使用分号的一些空语句也不会使警告静音(实际上它只会添加关于空语句的附加警告):

if x == "hello" then
    ;
elseif ...
Run Code Online (Sandbox Code Playgroud)

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

if x ~= "hello" then
    if x == "world" then
        print(17)
    else
        error("impossible")
    end
end
Run Code Online (Sandbox Code Playgroud)

Ton*_*nyH 7

CLI和选项.luacheckrc很好,但我也发现内联注释最有用。

此页面:Luacheck Inline Commandsl显示了许多选项。例如:-- luacheck:ignore 111将禁用非标准全局警告。另一个有趣的宝石:pushpop

-- luacheck: push ignore foo
foo() -- No warning.
-- luacheck: pop
foo() -- Warning is emitted.
Run Code Online (Sandbox Code Playgroud)

这使您可以禁用规则或不同的 lint 功能,然后快速撤消它。


Pig*_*let 6

luacheck test.lua --ignore 542
Run Code Online (Sandbox Code Playgroud)

请参阅Luacheck文档. 命令行界面

CLI选项--ignore, - enable和--only以及相应的配置选项允许使用警告代码上的模式匹配过滤警告,......

警告清单

代码| 描述

542 | 一个空的if分支.

或者,也可以通过ignore在.luacheckrc 配置文件中设置选项来禁用警告:

ignore = {"542"}
Run Code Online (Sandbox Code Playgroud)

我个人不喜欢忽视警告.我更愿意解决他们的原因.

因此,我对您的特定问题的解决方案是简单地重新排列条件.这不需要额外的if层,就像你提出的替代方案一样.

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

f("world")
Run Code Online (Sandbox Code Playgroud)