Search code examples
lualuacheck

How to ignore Luacheck warnings?


The Luacheck linter produces a warning when an if statement branch doesn't include any statements. For example, if I have a file called test.lua with the following code

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")

Then running luacheck test.lua will produce the following diagnostic

Checking test.lua                                 1 warning

    test.lua:2:21: empty if branch

Total: 1 warning / 0 errors in 1 file

Is there a way to work around this warning? As far as I know there is no configuration option to disable it and trying to some empty statements with a semicolon would not silence the warning either (in fact it would just add an additional warning about the empty statement):

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

At the moment the only workaround I can think of involves creating an extra layer of if statements, which I think is less clear than the original version.

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

Solution

  • luacheck test.lua --ignore 542
    

    Please refer to the Luacheck documentation. 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.

    Alternatively, it is also possible to disable a warning by setting the ignore option in a .luacheckrc Configuration File:

    ignore = {"542"}
    

    Personally I don't like ignoring warnings. I prefer to fix their cause.

    So my solution to your particular problem would be to simply rearrange the conditionals. This does not require an extra if layer as in the alternative you came up with.

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