Scroll to navigation

LUACHECK(1) luacheck LUACHECK(1)

NAME

luacheck - luacheck Documentation

Contents:

LIST OF WARNINGS

Warnings produced by Luacheck are categorized using three-digit warning codes. Warning codes can be displayed in CLI output using --codes CLI option or codes config option. Errors also have codes starting with zero.
Code Description
011 A syntax error.
021 An invalid inline option.
022 An unpaired inline push directive.
023 An unpaired inline pop directive.
111 Setting an undefined global variable.
112 Mutating an undefined global variable.
113 Accessing an undefined global variable.
121 Setting a read-only global variable.
122 Mutating a read-only global variable.
131 Unused implicitly defined global variable.
211 Unused local variable.
212 Unused argument.
213 Unused loop variable.
221 Local variable is accessed but never set.
231 Local variable is set but never accessed.
232 An argument is set but never accessed.
233 Loop variable is set but never accessed.
241 Local variable is mutated but never accessed.
311 Value assigned to a local variable is unused.
312 Value of an argument is unused.
313 Value of a loop variable is unused.
314 Value of a field in a table literal is unused.
321 Accessing uninitialized local variable.
331 Value assigned to a local variable is mutated but never accessed.
341 Mutating uninitialized local variable.
411 Redefining a local variable.
412 Redefining an argument.
413 Redefining a loop variable.
421 Shadowing a local variable.
422 Shadowing an argument.
423 Shadowing a loop variable.
431 Shadowing an upvalue.
432 Shadowing an upvalue argument.
433 Shadowing an upvalue loop variable.
511 Unreachable code.
512 Loop can be executed at most once.
521 Unused label.
531 Left-hand side of an assignment is too short.
532 Left-hand side of an assignment is too long.
541 An empty do end block.
542 An empty if branch.
551 An empty statement.
611 A line consists of nothing but whitespace.
612 A line contains trailing whitespace.
621 Inconsistent indentation (SPACE followed by TAB).

Global variables

For each file, Luacheck builds list of defined globals which can be used there. By default only globals from Lua standard library are defined; custom globals can be added using --globals CLI option or globals config option, and version of standard library can be selected using --std CLI option or std config option. When an undefined global is set, mutated or accessed, Luacheck produces a warning.

Read-only globals

By default, all standard globals except _G and package are marked as read-only, so that setting or mutating them produces a warning. Custom read-only globals can be added using --read-globals CLI option or read_globals config option.

Implicitly defined globals

Luacheck can be configured to consider globals assigned under some conditions to be defined implicitly. When -d/--allow_defined CLI option or allow_defined config option is used, all assignments to globals define them; when -t/--allow_defined_top CLI option or allow_defined_top config option is used, assignments to globals in the top level function scope (also known as main chunk) define them. A warning is produced when an implicitly defined global is not accessed anywhere.

Modules

Files can be marked as modules using -m/--module CLI option or module config option to simulate semantics of the deprecated module function. Globals implicitly defined inside a module are considired part of its interface, are not visible outside and are not reported as unused. Assignments to other globals are not allowed, even to defined ones.

Unused variables and values

Luacheck generates warnings for all unused local variables except one named _. It also detects variables which are set but never accessed or accessed but never set.

Unused values and uninitialized variables

For each value assigned to a local variable, Luacheck computes set of expressions where it could be used. Warnings are produced for unused values (when a value can't be used anywhere) and for accessing uninitialized variables (when no values can reach an expression). E.g. in the following snippet value assigned to foo on line 1 is unused, and variable bar is uninitialized on line 9:

local foo = expr1()
local bar
if condition() then
   foo = expr2()
   bar = expr3()
else
   foo = expr4()
   print(bar)
end
return foo, bar


Secondary values and variables

Unused value assigned to a local variable is secondary if its origin is the last item on the RHS of assignment, and another value from that item is used. Secondary values typically appear when result of a function call is put into locals, and only some of them are later used. For example, here value assigned to b is secondary, value assigned to c is used, and value assigned to a is simply unused:

local a, b, c = f(), g()
return c


A variable is secondary if all values assigned to it are secondary. In the snippet above, b is a secondary variable.

Warnings related to unused secondary values and variables can be removed using -s/--no-unused-secondaries CLI option or unused_secondaries config option.

Shadowing declarations

Luacheck detects declarations of local variables shadowing previous declarations, unless the variable is named _. If the previous declaration is in the same scope as the new one, it is called redefining.

Note that it is not necessary to define a new local variable when overwriting an argument:

local function f(x)
   local x = x or "default" -- bad
end
local function f(x)
   x = x or "default" -- good
end


Control flow and data flow issues

The following control flow and data flow issues are detected:
  • Unreachable code and loops that can be executed at most once (e.g. due to an unconditional break);
  • Unused labels;
  • Unbalanced assignments;
  • Empty blocks.
  • Empty statements (semicolons without preceding statements).

Whitespace issues

Luacheck detects some common whitespace issues, such as trailing whitespace.

COMMAND LINE INTERFACE

luacheck program accepts files, directories and rockspecs as arguments. They can be filtered using --include-files and --exclude-files options, see below.
  • Given a file, luacheck will check it.
  • Given -, luacheck will check stdin.
  • Given a directory, luacheck will check all files within it, selecting only files with .lua extension unless --include-files option is used. This feature requires LuaFileSystem (installed automatically if LuaRocks was used to install Luacheck).
  • Given a rockspec (a file with .rockspec extension), luacheck will check all files with .lua extension mentioned in the rockspec in build.install.lua, build.install.bin and build.modules tables.

The output of luacheck consists of separate reports for each checked file and ends with a summary:

$ luacheck src
Checking src/bad_code.lua                         5 warnings
    src/bad_code.lua:3:16: unused variable helper
    src/bad_code.lua:3:23: unused variable length argument
    src/bad_code.lua:7:10: setting non-standard global variable embrace
    src/bad_code.lua:8:10: variable opt was previously defined as an argument on line 7
    src/bad_code.lua:9:11: accessing undefined variable hepler
Checking src/good_code.lua                        OK
Checking src/python_code.lua                      1 error
    src/python_code.lua:1:6: expected '=' near '__future__'
Checking src/unused_code.lua                      9 warnings
    src/unused_code.lua:3:18: unused argument baz
    src/unused_code.lua:4:8: unused loop variable i
    src/unused_code.lua:5:13: unused variable q
    src/unused_code.lua:7:11: unused loop variable a
    src/unused_code.lua:7:14: unused loop variable b
    src/unused_code.lua:7:17: unused loop variable c
    src/unused_code.lua:13:7: value assigned to variable x is unused
    src/unused_code.lua:14:1: value assigned to variable x is unused
    src/unused_code.lua:22:1: value assigned to variable z is unused
Total: 14 warnings / 1 error in 4 files


luacheck exits with 0 if no warnings or errors occurred and with a positive number otherwise.

Command line options

Short options that do not take an argument can be combined into one, so that -qqu is equivalent to -q -q -u. For long options, both --option value or --option=value can be used.

Options taking several arguments can be used several times; --ignore foo --ignore bar is equivalent to --ignore foo bar.

Note that options that may take several arguments, such as --globals, should not be used immediately before positional arguments; given --globals foo bar file.lua, luacheck will consider all foo, bar and file.lua global and then panic as there are no file names left.

Option Meaning
-g | --no-global Filter out warnings related to global variables.
-u | --no-unused Filter out warnings related to unused variables and values.
-r | --no-redefined Filter out warnings related to redefined variables.
-a | --no-unused-args Filter out warnings related to unused arguments and loop variables.
-s | --no-unused-secondaries Filter out warnings related to unused variables set together with used ones. See secondaryvaluesandvariables
--no-self Filter out warnings related to implicit self argument.
--std <std> Set standard globals. <std> can be one of: 0.0 • 2 _G - globals of the Lua interpreter luacheck runs on (default); • 2 lua51 - globals of Lua 5.1; • 2 lua52 - globals of Lua 5.2; • 2 lua52c - globals of Lua 5.2 compiled with LUA_COMPAT_ALL; • 2 lua53 - globals of Lua 5.3; • 2 lua53c - globals of Lua 5.3 compiled with LUA_COMPAT_5_2; • 2 luajit - globals of LuaJIT 2.0; • 2 ngx_lua - globals of Openresty lua-nginx-module with LuaJIT 2.0; • 2 rockspec - globals allowed in rockspecs; • 2 min - intersection of globals of Lua 5.1, Lua 5.2, Lua 5.3 and LuaJIT 2.0; • 2 max - union of globals of Lua 5.1, Lua 5.2, Lua 5.3 and LuaJIT 2.0; • 2 busted - globals added by Busted 2.0; • 2 none - no standard globals. 168u See Sets of standard globals
--globals [<global>] ... Add custom globals on top of standard ones.
--read-globals [<global>] ... Add read-only globals.
--new-globals [<global>] ... Set custom globals. Removes custom globals added previously.
--new-read-globals [<global>] ... Set read-only globals. Removes read-only globals added previously.
-c | --compat Equivalent to --std max.
-d | --allow-defined Allow defining globals implicitly by setting them. See implicitlydefinedglobals
-t | --allow-defined-top Allow defining globals implicitly by setting them in the top level scope. See implicitlydefinedglobals
-m | --module Limit visibility of implicitly defined globals to their files. See modules
--ignore | -i <patt> [<patt>] ... Filter out warnings matching patterns.
--enable | -e <patt> [<patt>] ... Do not filter out warnings matching patterns.
--only | -o <patt> [<patt>] ... Filter out warnings not matching patterns.
--no-inline Disable inline options.
--config <config> Path to custom configuration file (default: .luacheckrc).
--no-config Do not look up custom configuration file.
--filename <filename> Use another filename in output, for selecting configuration overrides and for file filtering.
--exclude-files <glob> [<glob>] ... Do not check files matching these globbing patterns. Recursive globs such as **/*.lua are supported.
--include-files <glob> [<glob>] ... Do not check files not matching these globbing patterns.
--cache [<cache>] Path to cache file. (default: .luacheckcache). See Caching
--no-cache Do not use cache.
-j | --jobs Check <jobs> files in parallel. Requires LuaLanes. Default number of jobs is set to number of available processing units.
--formatter <formatter> Use custom formatter. <formatter> must be a module name or one of: 0.0 • 2 TAP - Test Anything Protocol formatter; • 2 JUnit - JUnit XML formatter; • 2 plain - simple warning-per-line formatter; • 2 default - standard formatter. 168u
-q | --quiet Suppress report output for files without warnings. 0.0 • 2 -qq - Suppress output of warnings. • 2 -qqq - Only output summary. 168u
--codes Show warning codes.
--ranges Show ranges of columns related to warnings.
--no-color Do not colorize output.
-v | --version Show version of Luacheck and its dependencies and exit.
-h | --help Show help and exit.

Patterns

CLI options --ignore, --enable and --only and corresponding config options allow filtering warnings using pattern matching on warning codes, variable names or both. If a pattern contains a slash, the part before slash matches warning code and the part after matches variable name. Otherwise, if a pattern contains a letter or underscore, it matches variable name. Otherwise, it matches warning code. E.g.:
Pattern Matching warnings
4.2 Shadowing declarations of arguments or redefining them.
.*_ Warnings related to variables with _ suffix.
4.2/.*_ Shadowing declarations of arguments with _ suffix or redefining them.

Unless already anchored, patterns matching variable names are anchored at both sides and patterns matching warning codes are anchored at their beginnings. This allows one to filter warnings by category (e.g. --only 1 focuses luacheck on global-related warnings).

Sets of standard globals

CLI option --stds allows combining built-in sets described above using +. For example, --std max is equivalent to --std=lua51+lua52+lua53. Leading plus sign adds new sets to default one instead of replacing it. For instance, --std +busted is suitable for checking test files that use Busted testing framework. Custom sets of globals can be defined by mutating global variable stds in config. See custom_stds

Formatters

CLI option --formatter allows selecting a custom formatter for luacheck output. A custom formatter is a Lua module returning a function with three arguments: report as returned by luacheck module (see report), array of file names and table of options. Options contain values assigned to quiet, color, limit, codes, ranges and formatter options in CLI or config. Formatter function must return a string.

Caching

If LuaFileSystem is available, Luacheck can cache results of checking files. On subsequent checks, only files which have changed since the last check will be rechecked, improving run time significantly. Changing options (e.g. defining additional globals) does not invalidate cache. Caching can be enabled by using --cache <cache> option or cache config option. Using --cache without an argument or setting cache config option to true sets .luacheckcache as the cache file. Note that --cache must be used every time luacheck is run, not on the first run only.

Stable interface for editor plugins and tools

Command-line interface of Luacheck can change between minor releases. Starting from 0.11.0 version, the following interface is guaranteed at least till 1.0.0 version, and should be used by tools using Luacheck output, e.g. editor plugins.
  • Luacheck should be started from the directory containing the checked file.
  • File can be passed through stdin using - as argument or using a temporary file. Real filename should be passed using --filename option.
  • Plain formatter should be used. It outputs one issue (warning or error) per line.
  • To get precise error location, --ranges option can be used. Each line starts with real filename (passed using --filename), followed by :<line>:<start_column>-<end_column>:, where <line> is line number on which issue occurred and <start_column>-<end_column> is inclusive range of columns of token related to issue. Numbering starts from 1. If --ranges is not used, end column and dash is not printed.
  • To get warning and error codes, --codes option can be used. For each line, substring between parentheses contains three digit issue code, prefixed with E for errors and W for warnings. Lack of such substring indicates a fatal error (e.g. I/O error).
  • The rest of the line is warning message.

If compatibility with older Luacheck version is desired, output of luacheck --help can be used to get its version. If it contains string 0.<minor>.<patch>, where <minor> is at least 11 and patch is any number, interface described above should be used.

CONFIGURATION FILE

luacheck tries to load configuration from .luacheckrc file in the current directory. If not found, it will look for it in the parent directory and so on, going up until it reaches file system root. Path to config can be set using --config option, in which case it will be used during recursive loading. Config loading can be disabled using --no-config flag.

Config is simply a Lua script executed by luacheck. It may set various options by assigning to globals or by returning a table with option names as keys.

Config options

Option Type Default value
color Boolean true
codes Boolean false
formatter String or function "default"
cache Boolean or string false
jobs Positive integer 1
exclude_files Array of strings {}
include_files Array of strings (Include all files)
global Boolean true
unused Boolean true
redefined Boolean true
unused_args Boolean true
unused_secondaries Boolean true
self Boolean true
std String or set of standard globals "_G"
globals Array of strings {}
new_globals Array of strings (Do not overwrite)
read_globals Array of strings {}
new_read_globals Array of strings (Do not overwrite)
compat Boolean false
allow_defined Boolean false
allow_defined_top Boolean false
module Boolean false
ignore Array of patterns (see patterns) {}
enable Array of patterns {}
only Array of patterns (Do not filter)
inline Boolean true

An example of a config which makes luacheck ensure that only globals from the portable intersection of Lua 5.1, Lua 5.2, Lua 5.3 and LuaJIT 2.0 are used, as well as disables detection of unused arguments:

std = "min"
ignore = {"212"}


Custom sets of globals

std option allows setting a custom standard set of globals using a table. In that table, string keys are globals, and string in array part are read-only globals.

Additionally, custom sets can be given names by mutating global stds variable. For example, when using LPEG library, it makes sense to access its functions tersely using globals. In that case, the following config allows removing false positives related to global access easily:

stds.lpeg = require "lpeg"


local lpeg = require "lpeg"
local function parse1(...)
   -- This function only uses lpeg functions as globals.
   local _ENV = lpeg
   -- luacheck: std lpeg
   local digit, space = R "09", S " "
   -- ...
end
local function parse2(...)
   -- This function uses lpeg functions as well as standard globals.
   local _ENV = setmetatable({}, {__index = function(_, k) return _ENV[k] or lpeg[k] end})
   -- luacheck: std +lpeg
   local digit, space = R "09", S " "
   local number = C(digit^1) / tonumber
   -- ...
end


Per-file and per-path overrides

The environment in which luacheck loads the config contains a special global files. When checking a file <path>, luacheck will override options from the main config with entries from files[<glob>] if <glob> matches <path>, applying entries for more general globs first. For example, the following config re-enables detection of unused arguments only for files in src/dir, but not for files ending with _special.lua, and allows using Busted globals within spec/:

std = "min"
ignore = {"212"}
files["src/dir"] = {enable = {"212"}}
files["src/dir/**/*_special.lua"] = {ignore = {"212"}}
files["spec"] = {std = "+busted"}


Note that files table supports autovivification, so that

files["src/dir"].enable = {"212"}


and

files["src/dir"] = {enable = {"212"}}


are equivalent.

INLINE OPTIONS

Luacheck supports setting some options directly in the checked files using inline configuration comments. An inline configuration comment starts with luacheck: label, possibly after some whitespace. The body of the comment should contain comma separated options, where option invocation consists of its name plus space separated arguments. It can also contain notes enclosed in balanced parentheses, which are ignored. The following options are supported:
Option Number of arguments
global 0
unused 0
redefined 0
unused args 0
unused secondaries 0
self 0
compat 0
module 0
allow defined 0
allow defined top 0
std 1
globals 0+
new globals 0+
read globals 0+
new read globals 0+
ignore 0+ (without arguments everything is ignored)
enable 1+
only 1+

Options that take no arguments can be prefixed with no to invert their meaning. E.g. --luacheck: no unused args disables unused argument warnings.

Part of the file affected by inline option dependes on where it is placed. If there is any code on the line with the option, only that line is affected; otherwise, everything till the end of the current closure is. In particular, inline options at the top of the file affect all of it:

-- luacheck: globals g1 g2, ignore foo
local foo = g1(g2) -- No warnings emitted.
-- The following unused function is not reported.
local function f() -- luacheck: ignore
   -- luacheck: globals g3
   g3() -- No warning.
end
g3() -- Warning is emitted as the inline option defining g3 only affected function f.


For fine-grained control over inline option visibility use luacheck: push and luacheck: pop directives:

-- luacheck: push ignore foo
foo() -- No warning.
-- luacheck: pop
foo() -- Warning is emitted.


Inline options can be completely disabled using --no-inline CLI option or inline config option.

LUACHECK MODULE

Use local luacheck = require "luacheck" to import luacheck module. It contains the following functions:
  • luacheck.get_report(source): Given source string, returns analysis data (a table).
  • luacheck.process_reports(reports, options): Processes array of analysis reports and applies options. reports[i] uses options, options[i], options[i][1], options[i][2], ... as options, overriding each other in that order. Options table is a table with fields similar to config options; see options. Analysis reports with field fatal are ignored. process_reports returns final report, see Report format.
  • luacheck.check_strings(sources, options): Checks array of sources using options, returns final report. Tables with field fatal within sources array are ignored.
  • luacheck.check_files(files, options): Checks array of files using options, returns final report. Open file handles can passed instead of filenames, in which case they will be read till EOF and closed.
  • luacheck.get_message(issue): Returns a string message for an issue, see Report format.

luacheck._VERSION contains Luacheck version as a string in MAJOR.MINOR.PATCH format.

Using luacheck as a function is equivalent to calling luacheck.check_files.

Report format

A final report is an array of file reports plus fields warnings, errors and fatals containing total number of warnings, errors and fatal errors, correspondingly.

A file report is an array of issues (warnings or errors). If a fatal error occurred while checking a file, its report will have fatal field containing error type and msg field containing error message.

An issue is a table with field code indicating its type (see warnings), and fields line, column and end_column pointing to the source of the warning. name field may contain name of related variable. Issues of some types can also have additional fields:

Codes Additional fields
011 msg field contains syntax error message.
111 module field indicates that assignment is to a non-module global variable.
211 func field indicates that unused variable is a function.
211 recursive field indicates that unused function is recursive.
211 mutually_recursive field is set for unused mutually recursive functions.
314 field field contains string representation of ununsed field or index.
4.. prev_line and prev_column fields contain location of the overwritten definition.
521 label field contains label name.

Other fields may be present for internal reasons.

This is documentation for 0.17.1 version of Luacheck, a linter for Lua.

AUTHOR

Peter Melnichenko

COPYRIGHT

2016 - 2016, Peter Melnichenko
December 22, 2016 0.17.1