Luacheck Documentation

repository·master·Indexed 24 days ago

https://github.com/mpeterv/luacheck

Luacheck is a static analyzer and linter for Lua that detects issues such as undefined globals, unused variables, uninitialized variables, and unreachable code. It supports Lua 5.1, 5.2, 5.3, and LuaJIT. The tool provides a command-line interface for analyzing files, directories, and rockspecs, and offers integration for editors like Vim, Visual Studio Code, and Emacs. Key features include configurable standard globals, cyclomatic complexity limits, custom output formatters, and result caching via LuaFileSystem.

Tokens
9.3K
Snippets
13
Records
50
Agent score
81%

What's inside Luacheck

  1. Control inline option scope and visibility

    master

    The scope of an inline option depends on its placement:

    1. On a line with code: Only that specific line is affected.
    2. On a line without code: Everything from that line until the end of the current closure (e.g., the end of a function or block) is affected.
    3. At the top of a file: The entire file is affected.

    For precise control over when options are active, use the push and pop directives to create a temporary scope for configuration.

    -- luacheck: push ignore foo
    foo() -- No warning.
    -- luacheck: pop
    foo() -- Warning is emitted.
    
    -- Example of closure scope:
    local function f()
       -- luacheck: globals g3
       g3() -- No warning.
    end
    
    g3() -- Warning is emitted because the option only affected function f.
  2. Use module semantics with `--module`

    master

    To simulate the behavior of the deprecated Lua module function, use the -m / --module (CLI) or module (config) option.

    When a file is marked as a module:

    • Globals implicitly defined inside the module are considered part of its interface.
    • These globals are not visible outside the module and are not reported as unused.
    • Assignments to any other globals (even if already defined) are not allowed.
  3. Filter warnings using pattern matching

    master

    You can filter warnings using the --ignore, --enable, and --only CLI options (or their config equivalents) by providing patterns.

    Pattern Syntax:

    • code/variable: If a pattern contains a slash, the part before the slash matches the warning code and the part after matches the variable name.
    • variable: If a pattern contains a letter or underscore (but no slash), it matches the variable name.
    • code: Otherwise, it matches the warning code.

    Anchoring Rules:

    • Variable name patterns are anchored at both sides (exact match required unless specified otherwise).
    • Warning code patterns are anchored at the beginning.

    Examples:

    • 4.2: Matches warning code 4.2.
    • .*_: Matches warnings related to variables ending with an underscore.
    • 4.2/.*_: Matches shadowing or redefining of arguments that have an underscore suffix.
  4. How Luacheck loads configuration files

    master

    Luacheck searches for a configuration file named .luacheckrc in the current directory, then moves up the directory tree until it reaches the root.

    Manual Configuration:

    • Use the --config <path> CLI option to specify a custom configuration file. Paths within this config are interpreted relative to the config file's directory.
    • Use the --no-config flag to disable configuration loading entirely.

    Default Configuration Locations: If no explicit config is provided via CLI, Luacheck looks in:

    • Windows: %LOCALAPPDATA%\Luacheck\.luacheckrc
    • OS X/macOS: ~/Library/Application Support/Luacheck/.luacheckrc
    • Other systems: $XDG_CONFIG_HOME/luacheck/.luacheckrc or ~/.config/luacheck/.luacheckrc

    Config Format: A configuration file is a Lua script. You can set options by assigning values to global variables or by returning a table where keys are option names.

  5. Understand the Luacheck report format

    master

    Luacheck returns data in a structured hierarchical format:

    Final Report

    An array of file reports, plus summary fields:

    • warnings: Total number of warnings.
    • errors: Total number of errors.
    • fatals: Total number of fatal errors.

    File Report

    An array of issues (warnings or errors). If a fatal error occurred during the check of a file, the report includes:

    • fatal: The error type.
    • msg: The error message.

    Issue

    A table representing a specific finding:

    • code: The type of issue (e.g., warning or error code).
    • line: The line number in the source.
    • column: The starting column.
    • end_column: The ending column.
    • name: (Optional) The name of the related variable.
    • msg: (Optional) The error message (via get_message or directly).
  6. Stable interface for editor plugins and tools

    master

    For tools (like editor plugins) that parse Luacheck output, use the stable interface guaranteed from version 0.11.0 through 1.0.0.

    Integration Requirements:

    1. Working Directory: Start Luacheck from the directory containing the file being checked.
    2. Input: Pass files via stdin using - as an argument, or use a temporary file with the --filename <path> option.
    3. Formatter: Use the plain formatter (outputs one issue per line).
    4. Error Location: Use the --ranges option for precise locations. Each line will follow the format: <filename>:<line>:<start_column>-<end_column>:<message>
    5. Codes: Use the --codes option to get warning/error codes. Codes appear in parentheses as a three-digit number prefixed with E (error) or W (warning).

    Example Output Format (with --ranges and --codes): myfile.lua:10:5-8:W001 variable 'x' is unused

  7. Install Luacheck via LuaRocks

    master

    To install Luacheck using the LuaRocks package manager, run the following command in your terminal. You may need to use sudo depending on your system configuration.

    For parallel checking support, you should also install lanes via LuaRocks.

    luarocks install luacheck
    # Optional: for parallel checking
    luarocks install lanes
  8. Use inline configuration options in Lua files

    master

    Luacheck allows you to set configuration options directly within your Lua source files using inline comments. These inline options have the highest priority and will overwrite settings from both your configuration files and CLI arguments.

    An inline configuration comment must start with the luacheck: label. The body of the comment contains comma-separated options. For options that require arguments, provide the name followed by space-separated values. You can also include notes in balanced parentheses () which will be ignored.

    To disable an option that takes no arguments, prefix it with no (e.g., --luacheck: no unused args).

    -- luacheck: globals g1 g2, ignore foo
    local foo = g1(g2) -- No warnings emitted.
  9. How to run luacheck on files, directories, and rockspecs

    master

    The luacheck program accepts several types of arguments to define the scope of the check:

    • Files: Checking a specific file.
    • Stdin: Use - to check content from standard input.
    • Directories: Checks all .lua files within the directory. This requires LuaFileSystem to be installed. You can use --include-files to include non-Lua files.
    • Rockspecs: Checking a .rockspec file will cause luacheck to check all .lua files mentioned in the build.install.lua, build.install.bin, and build.modules tables.

    You can further refine the scope using --include-files <glob> and --exclude-files <glob> (recursive globs like **/*.lua are supported).

    luacheck src
  10. Apply per-file and per-path configuration overrides

    master

    Luacheck provides a special files global in the configuration environment. You can use glob patterns to override settings for specific files or directories. When a file matches multiple patterns, Luacheck applies entries for more general globs first, then more specific ones.

    Note that the files table supports autovivification, meaning you can assign directly to a sub-key.

    std = "min"
    ignore = {"212"}
    
    -- Overriding settings for a specific directory
    files["src/dir"] = {enable = {"212"}}
    
    -- Overriding settings for specific file patterns
    files["src/dir/**/*_special.lua"] = {ignore = {"212"}}
  11. Avoid shadowing and redefining variables

    master

    Luacheck detects when you declare a local variable that shadows a previous declaration (unless named _). If the declaration is in the same scope, it is flagged as redefining.

    Best Practice: When updating an argument, do not use local. Instead, assign to the argument directly.

    -- BAD: Redefines the argument x
    local function f(x)
       local x = x or "default"
    end
    
    -- GOOD: Updates the argument x directly
    local function f(x)
       x = x or "default"
    end