### Install Luacheck via LuaRocks Source: https://github.com/mpeterv/luacheck/blob/master/README.md Use this command to install the Luacheck package globally. ```bash luarocks install luacheck ``` -------------------------------- ### Luacheck CLI Example Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md Demonstrates how to use the luacheck command-line tool to check files in a directory. The output shows warnings and errors found in the checked files, along with a summary. ```default $ 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 output example Source: https://github.com/mpeterv/luacheck/blob/master/README.md Example of the console output generated when running Luacheck on a project. ```text Checking src/good_code.lua OK Checking src/bad_code.lua 3 warnings 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 Checking src/python_code.lua 1 error src/python_code.lua:1:6: expected '=' near '__future__' Checking extra_file.lua 5 warnings extra_file.lua:3:18: unused argument baz extra_file.lua:4:8: unused loop variable i extra_file.lua:13:7: accessing uninitialized variable a extra_file.lua:14:1: value assigned to variable x is unused extra_file.lua:21:7: variable z is never accessed Checking another_file.lua 2 warnings another_file.lua:2:7: unused variable height another_file.lua:3:7: accessing undefined variable heigth Total: 10 warnings / 1 error in 5 files ``` -------------------------------- ### Integrate Luacheck programmatically Source: https://context7.com/mpeterv/luacheck/llms.txt A complete example showing how to wrap luacheck.check_files, process the report structure, and handle custom output formatting. ```lua local luacheck = require "luacheck" -- Custom lint function with detailed output local function lint_project(file_paths, options) options = options or {} -- Default options local opts = { std = options.std or "lua53", ignore = options.ignore or {}, globals = options.globals or {}, max_line_length = options.max_line_length or 120, max_cyclomatic_complexity = options.max_cyclomatic_complexity or false } -- Check all files local report = luacheck.check_files(file_paths, opts) -- Build result structure local result = { success = report.warnings == 0 and report.errors == 0 and report.fatals == 0, summary = { files_checked = #file_paths, warnings = report.warnings, errors = report.errors, fatals = report.fatals }, files = {} } -- Process each file report for i, file_report in ipairs(report) do local file_result = { path = file_paths[i], issues = {} } if file_report.fatal then table.insert(file_result.issues, { type = "fatal", message = file_report.msg }) else for _, issue in ipairs(file_report) do table.insert(file_result.issues, { type = issue.code:sub(1, 1) == "0" and "error" or "warning", code = issue.code, line = issue.line, column = issue.column, end_column = issue.end_column, message = luacheck.get_message(issue) }) end end table.insert(result.files, file_result) end return result end -- Usage example local files = {"src/main.lua", "src/utils.lua", "lib/helpers.lua"} local result = lint_project(files, { std = "lua53+love", ignore = {"212"}, -- Ignore unused arguments globals = {"GAME_STATE"}, max_line_length = 100, max_cyclomatic_complexity = 15 }) -- Output results if result.success then print("All checks passed!") else print(string.format( "Found %d warnings, %d errors, %d fatal errors", result.summary.warnings, result.summary.errors, result.summary.fatals )) for _, file in ipairs(result.files) do if #file.issues > 0 then print("\n" .. file.path .. ":") for _, issue in ipairs(file.issues) do if issue.line then print(string.format( " %d:%d [%s] %s", issue.line, issue.column, issue.code, issue.message )) else print(string.format(" [%s] %s", issue.type, issue.message)) end end end end end -- Return exit code for CI integration os.exit(result.success and 0 or 1) ``` -------------------------------- ### Development and Testing Commands Source: https://github.com/mpeterv/luacheck/blob/master/README.md Commands for installing the development version, running Luacheck from source, and executing the test suite. ```bash luarocks make ``` ```bash lua -e 'package.path="./src/?.lua;./src/?/init.lua;"..package.path' bin/luacheck.lua ... ``` ```bash busted ``` -------------------------------- ### Luacheck Inline Options Example Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/inline.md Demonstrates the use of `globals` and `ignore` inline options, showing how they affect warnings for defined variables and unused code. ```lua -- 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. ``` -------------------------------- ### Install Luacheck via LuaRocks Source: https://context7.com/mpeterv/luacheck/llms.txt Use LuaRocks to install the Luacheck package and optional dependencies like LuaLanes for parallel processing. ```bash # Install luacheck via LuaRocks luarocks install luacheck # For parallel checking, also install LuaLanes luarocks install lanes ``` -------------------------------- ### Custom Luacheck Configuration Example Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/config.md Use this configuration to enforce a minimal set of standard globals across Lua versions and disable unused argument detection. Ensure 'std' is set to 'min' and 'ignore' lists specific codes. ```lua std = "min" ignore = {"212"} ``` -------------------------------- ### Handle Shadowing Declarations Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/warnings.md Luacheck detects local variables shadowing previous declarations, unless the variable is named '_'. This example shows correct and incorrect ways to handle overwriting function arguments. ```lua local function f(x) local x = x or "default" -- bad end local function f(x) x = x or "default" -- good end ``` -------------------------------- ### Basic .luacheckrc Configuration Source: https://context7.com/mpeterv/luacheck/llms.txt Define project-wide settings in a .luacheckrc file. ```lua -- .luacheckrc -- Use Lua 5.3 standard globals std = "lua53" -- Ignore unused argument warnings (code 212) ignore = {"212"} -- Add custom globals globals = {"my_global", "another_global"} -- Add read-only globals read_globals = {"CONFIG", "DEBUG"} -- Set maximum line length max_line_length = 100 -- Disable color output color = false -- Enable warning codes in output codes = true -- Enable caching cache = true -- Set parallel jobs jobs = 4 ``` -------------------------------- ### Access and Build Documentation Source: https://github.com/mpeterv/luacheck/blob/master/README.md Commands for viewing documentation offline or generating it from source files. ```bash luarocks doc luacheck ``` ```bash sphinx-build docsrc doc ``` -------------------------------- ### Run Luacheck Basic Commands Source: https://context7.com/mpeterv/luacheck/llms.txt Execute linting on files, directories, or streams using the Luacheck CLI. ```bash # Check a single file luacheck myfile.lua # Check multiple files luacheck src/main.lua src/utils.lua # Check an entire directory (requires LuaFileSystem) luacheck src/ # Check a rockspec file luacheck myproject-1.0-1.rockspec # Check from stdin cat myfile.lua | luacheck - ``` -------------------------------- ### Integrate Luacheck with Editors Source: https://context7.com/mpeterv/luacheck/llms.txt Use the recommended CLI flags for machine-readable output in editor plugins. ```bash # Recommended interface for editor plugins # Run from the directory containing the file cd /path/to/project # Check file with plain formatter, codes, and ranges luacheck --formatter plain --codes --ranges myfile.lua ``` -------------------------------- ### Configuration Options Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md Luacheck provides several command-line options to customize its behavior, particularly regarding configuration files and filename handling. ```APIDOC ## Configuration Options ### `--default-config ` #### Description Specifies a default path to a custom configuration file. This option is used if `--config` is not provided and no `.luacheckrc` file is found in the current directory. The default global locations are: * Windows: `%LOCALAPPDATA%\Luacheck\.luacheckrc` * OS X/macOS: `~/Library/Application Support/Luacheck/.luacheckrc` * Other systems: `$XDG_CONFIG_HOME/luacheck/.luacheckrc` or `~/.config/luacheck/.luacheckrc` ### `--no-default-config` #### Description Disables the use of any fallback configuration files. ### `--filename ` #### Description Assigns an alternative filename for output purposes. This is useful for selecting configuration overrides and for filtering files. ``` -------------------------------- ### Luacheck Configuration Options Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md This section details the command-line options available for configuring Luacheck's behavior, including caching, parallel processing, and output formatting. ```APIDOC ## Luacheck Command-Line Options ### Description Luacheck is a tool for linting Lua code. This documentation outlines its command-line options for customization. ### Options #### `--no-cache` * **Description**: Do not use the cache. * **Type**: Flag #### `-j | --jobs ` * **Description**: Check `` files in parallel. Requires [LuaLanes](http://cmr.github.io/lanes/). The default number of jobs is set to the number of available processing units. * **Type**: Integer * **Alias**: `-j` #### `--formatter ` * **Description**: Use a custom formatter. `` must be a module name or one of the following predefined formatters: * `TAP` - Test Anything Protocol formatter. * `JUnit` - JUnit XML formatter. * `visual_studio` - MSBuild/Visual Studio aware formatter. * `plain` - Simple warning-per-line formatter. * `default` - Standard formatter. * **Type**: String * **Required**: No * **Default**: `default` ``` -------------------------------- ### Configure Line Length and Complexity Limits Source: https://context7.com/mpeterv/luacheck/llms.txt Set constraints for code formatting and cyclomatic complexity. ```bash luacheck --max-line-length 80 src/ luacheck --no-max-line-length src/ luacheck --max-code-line-length 100 --max-string-line-length 200 --max-comment-line-length 80 src/ luacheck --max-cyclomatic-complexity 10 src/ ``` -------------------------------- ### Configure Standard Globals Source: https://context7.com/mpeterv/luacheck/llms.txt Define the target Lua environment or custom globals to avoid false positive warnings. ```bash # Use Lua 5.1 standard globals luacheck --std lua51 src/ # Use Lua 5.2 standard globals luacheck --std lua52 src/ # Use Lua 5.3 standard globals luacheck --std lua53 src/ # Use LuaJIT globals luacheck --std luajit src/ # Use OpenResty lua-nginx-module globals luacheck --std ngx_lua src/ # Use LOVE framework globals luacheck --std love src/ # Combine standard sets with + luacheck --std "lua51+love" src/ # Use maximum compatibility (union of all versions) luacheck --std max src/ # Use minimum compatibility (intersection of all versions) luacheck --std min src/ # Add custom read-only globals luacheck --read-globals DEBUG CONFIG src/ # Add custom writable globals luacheck --globals my_global another_global src/ # Add globals with field access luacheck --read-globals foo --globals foo.bar src/ ``` -------------------------------- ### Apply Per-Path Overrides Source: https://context7.com/mpeterv/luacheck/llms.txt Configure specific options for files or directories using glob patterns. ```lua -- .luacheckrc -- Global settings std = "lua53" ignore = {"212"} -- Ignore unused arguments globally -- Re-enable unused argument warnings for src/dir files["src/dir"] = { enable = {"212"} } -- Special handling for test files - ignore unused loop variables files["src/dir/**/*_special.lua"] = { ignore = {"212", "213"} } -- Allow LOVE framework globals in game files files["src/game/**/*.lua"] = { std = "+love" } -- Allow test framework globals in test files files["spec/**/*_spec.lua"] = { std = "+busted" } -- Exclude generated files from checking exclude_files = { "src/generated/**", "vendor/**", "**/node_modules/**" } -- Only check specific files when given a directory include_files = { "**/*.lua", "*.luacheckrc" } ``` -------------------------------- ### Configure Luacheck Inline Options Source: https://context7.com/mpeterv/luacheck/llms.txt Use push and pop directives to manage option scopes within Lua source files. ```lua -- luacheck: push ignore foo -- Within this scope, 'foo' warnings are ignored foo() -- No warning -- luacheck: pop -- After pop, normal settings resume foo() -- Warning: accessing undefined global 'foo' -- Nested push/pop for complex scenarios -- luacheck: push -- luacheck: std +love -- LOVE framework code here love.graphics.draw(image, 0, 0) -- luacheck: push no unused local x, y = get_position() -- No unused variable warning print(x) -- y is unused but no warning -- luacheck: pop -- luacheck: pop -- Back to original settings ``` -------------------------------- ### Luacheck CLI Flags Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md Configuration options for file inclusion, exclusion, and cache management. ```APIDOC ## CLI Flags ### --exclude-files [] ... - **Description**: Do not check files matching these globbing patterns. Recursive globs such as `**/*.lua` are supported. ### --include-files [] ... - **Description**: Do not check files not matching these globbing patterns. ### --cache [] - **Description**: Path to cache file. (default: `.luacheckcache`). See [Caching](#cache) ``` -------------------------------- ### Configure Globals in Config Files Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/config.md In configuration files, 'globals', 'new_globals', 'read_globals', and 'new_read_globals' can define globals and their fields using the same format as custom sets. ```lua read_globals = { server = { fields = { -- Allow mutating `server.sessions` with any keys... sessions = {read_only = false, other_fields = true}, -- other fields... } }, --- other globals... } ``` -------------------------------- ### Apply Per-File Configuration Overrides Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/config.md Use the 'files' table to override main configuration options for specific files matching glob patterns. More general globs are applied first. ```lua std = "min" ignore = {"212"} files["src/dir"] = {enable = {"212"}} files["src/dir/**/*_special.lua"] = {ignore = {"212"}} ``` -------------------------------- ### Configure Luacheck Caching Source: https://context7.com/mpeterv/luacheck/llms.txt Manage cache files to improve performance on repeated checks. ```bash luacheck --cache src/ luacheck --cache .my-luacheck-cache src/ luacheck --no-cache src/ ``` -------------------------------- ### Check Lua Files with check_files Source: https://context7.com/mpeterv/luacheck/llms.txt Analyze Lua files from the filesystem, supporting file handles and complex per-file configuration overrides. ```lua local luacheck = require "luacheck" -- Check files by path local files = { "src/main.lua", "src/utils.lua", "src/config.lua" } local report = luacheck.check_files(files) -- Report summary print(string.format( "Total: %d warnings, %d errors, %d fatal errors", report.warnings, report.errors, report.fatals )) -- Using luacheck as a callable (equivalent to check_files) local report2 = luacheck({ "src/main.lua", "src/utils.lua" }, { std = "lua53", unused = false -- Disable unused variable warnings }) -- Check with file handles local fh = io.open("script.lua", "r") local report3 = luacheck.check_files({fh}, {std = "luajit"}) -- File handle is automatically closed after reading -- Per-file options with nested overrides local report4 = luacheck.check_files(files, { std = "lua53", -- Base option for all files { -- Options for files[1] ignore = {"212"} -- Ignore unused arguments }, { -- Options for files[2] globals = {"DEBUG"}, {std = "+busted"} -- Additional nested override } }) -- Handle I/O errors gracefully local report5 = luacheck.check_files({"nonexistent.lua"}) if report5[1].fatal then print("Error:", report5[1].fatal, report5[1].msg) -- Output: Error: I/O cannot open nonexistent.lua: No such file or directory end ``` -------------------------------- ### Use Inline Options Source: https://context7.com/mpeterv/luacheck/llms.txt Control Luacheck behavior directly within Lua source files using comments. ```lua -- Inline options at file level affect the entire file -- luacheck: globals my_plugin_global -- Define multiple globals -- luacheck: globals g1 g2 g3, read globals r1 r2 local function process(unused_arg) -- luacheck: ignore unused_arg -- This specific warning is ignored for this line return 42 end -- Ignore all warnings for a function local function legacy_code() -- luacheck: ignore undefined_global() -- No warning local unused = 1 -- No warning end -- Set specific standard for this file -- luacheck: std lua51 -- Disable specific warning types -- luacheck: no unused args -- Set max line length for this file -- luacheck: max line length 200 ``` -------------------------------- ### Luacheck CLI Configuration Flags Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md Configuration options for controlling comment line length and cyclomatic complexity analysis in Luacheck. ```APIDOC ## CLI Options ### --max-comment-line-length - **Description**: Set maximum allowed length for comment lines (default: 120). ### --no-max-comment-line-length - **Description**: Do not limit comment line length. ### --max-cyclomatic-complexity - **Description**: Set maximum cyclomatic complexity for functions. ``` -------------------------------- ### Importing the Luacheck module Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/module.md Use this statement to load the Luacheck module into your Lua environment. ```lua local luacheck = require "luacheck" ``` -------------------------------- ### Autovivification in 'files' Table Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/config.md The 'files' table supports autovivification, meaning nested tables are created automatically as needed. This allows for more concise configuration. ```lua files["src/dir"].enable = {"212"} ``` ```lua files["src/dir"] = {enable = {"212"}} ``` -------------------------------- ### Define Custom Global Standards Source: https://context7.com/mpeterv/luacheck/llms.txt Create complex global object definitions and custom standards for reuse. ```lua -- .luacheckrc -- Define custom standard with detailed field access control std = { globals = {"app"}, -- Writable globals read_globals = { -- Define 'server' as read-only global with specific fields server = { fields = { config = {}, -- server.config is readable sessions = { read_only = false, -- server.sessions can be written other_fields = true -- server.sessions.* allows any subfields }, start = {}, stop = {} } }, -- Define 'utils' namespace utils = { fields = { log = { fields = { info = {}, warn = {}, error = {} } }, format = {} } } } } -- Create named custom standard for reuse stds.myframework = { read_globals = {"framework", "Component", "Service"} } -- Use the custom standard std = "lua53+myframework" ``` -------------------------------- ### Run Luacheck on files and directories Source: https://github.com/mpeterv/luacheck/blob/master/README.md Execute the linter against specific files or directories to identify code issues. ```bash luacheck src extra_file.lua another_file.lua ``` -------------------------------- ### Check stdin with filename Source: https://context7.com/mpeterv/luacheck/llms.txt Pipe code into Luacheck while providing a filename for configuration lookup. ```bash cat myfile.lua | luacheck --formatter plain --codes --ranges --filename myfile.lua - ``` -------------------------------- ### Analyze Lua Source Strings with get_report Source: https://context7.com/mpeterv/luacheck/llms.txt Analyze a single Lua source string and retrieve a detailed report of warnings and issues. ```lua local luacheck = require "luacheck" -- Analyze source code and get raw report local source = [[ local function greet(name) print("Hello, " .. username) -- 'username' is undefined end local unused_var = 42 -- unused variable ]] local report = luacheck.get_report(source) -- The report contains warnings array with issue details for _, warning in ipairs(report.warnings) do print(string.format( "Line %d, Column %d: [%s] %s", warning.line, warning.column, warning.code, warning.name or warning.msg )) end -- Output: -- Line 2, Column 26: [113] username -- Line 5, Column 7: [211] unused_var ``` -------------------------------- ### Luacheck CLI Flags Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md Configuration flags for controlling warning filters and standard global environments in Luacheck. ```APIDOC ## CLI Flags ### Description Configuration options for the Luacheck CLI to manage warning output and environment standards. ### Parameters #### Query Parameters - **-s | --no-unused-secondaries** (flag) - Optional - Filter out warnings related to unused variables set together with used ones. - **--no-self** (flag) - Optional - Filter out warnings related to implicit self argument. - **--std ** (string) - Optional - Set standard globals. Supported values: max, min, lua51, lua51c, lua52, lua52c, lua53, lua53c, luajit, ngx_lua, love, busted, rockspec, luacheckrc, none. ``` -------------------------------- ### Process analysis reports with Luacheck Source: https://context7.com/mpeterv/luacheck/llms.txt Use luacheck.process_reports to aggregate multiple raw reports with optional filtering, per-report configurations, and custom standard definitions. ```lua local luacheck = require "luacheck" -- Get raw reports for multiple sources local reports = { luacheck.get_report("return foo"), -- Undefined global luacheck.get_report("return math"), -- Standard global, OK luacheck.get_report("local x = 1"), -- Unused local luacheck.get_report("return return") -- Syntax error } -- Process with default options local result = luacheck.process_reports(reports) print(result.warnings, result.errors, result.fatals) -- Process with filtering options local filtered = luacheck.process_reports(reports, { std = "lua53", ignore = {"211"} -- Ignore unused locals }) -- Per-report options local custom = luacheck.process_reports(reports, { std = "none", -- No standard globals (global option) {ignore = {"113"}}, -- Ignore undefined globals for reports[1] {std = "lua53"}, -- Allow standard globals for reports[2] {}, -- Default for reports[3] {} -- Default for reports[4] }) -- Using custom standards local stds = { mylib = { read_globals = {"mylib"} } } local with_custom_std = luacheck.process_reports(reports, { std = "lua53+mylib" }, stds) ``` -------------------------------- ### Reversed Numeric For Loop Validation Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/warnings.md Demonstrates the correct syntax for reverse iteration using a negative step to avoid Luacheck warnings. ```lua -- Warning for this loop: -- numeric for loop goes from #(expr) down to 1 but loop step is not negative for i = #t, 1 do print(t[i]) end -- This loop is okay. for i = #t, 1, -1 do print(t[i]) end ``` -------------------------------- ### luacheck.check_files Source: https://context7.com/mpeterv/luacheck/llms.txt Checks Lua files from the filesystem or file handles with comprehensive options support. ```APIDOC ## luacheck.check_files ### Description Checks Lua files from the filesystem or file handles with comprehensive options support. This function can also be called directly as the main luacheck module function. ### Parameters - **files** (table) - Required - A list of file paths or file handles. - **options** (table) - Optional - Configuration options for the analysis. ### Response - **report** (table) - A report object containing summary counts and per-file issue details. ``` -------------------------------- ### luacheck.check_strings Source: https://context7.com/mpeterv/luacheck/llms.txt Checks multiple Lua source strings with configurable options and returns a processed report. ```APIDOC ## luacheck.check_strings ### Description Checks multiple Lua source strings with configurable options and returns a processed report. ### Parameters - **sources** (table) - Required - A list of Lua source strings. - **options** (table) - Optional - Configuration options for the analysis (e.g., std, ignore). ### Response - **report** (table) - A report object containing counts for warnings, errors, and fatals. ``` -------------------------------- ### Luacheck Usage as Function Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/module.md Using the `luacheck` module directly as a function is a shortcut for calling `luacheck.check_files`. ```APIDOC ## Luacheck Function Usage Using `luacheck` as a function is equivalent to calling `luacheck.check_files`. ### `luacheck(files, options)` **Description**: Checks an 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. **Parameters**: - **files** (table) - Required - An array of filenames or open file handles. - **options** (table) - Optional - Options to apply during checking. **Returns**: - table - The final report after checking all files. ``` -------------------------------- ### luacheck.get_report Source: https://context7.com/mpeterv/luacheck/llms.txt Analyzes a single Lua source string and returns a detailed report of detected issues. ```APIDOC ## luacheck.get_report ### Description Analyzes a Lua source string and returns a detailed report of all detected issues. ### Parameters - **source** (string) - Required - The Lua source code to analyze. ### Response - **report** (table) - A table containing a 'warnings' array with issue details including line, column, code, and message. ``` -------------------------------- ### Luacheck Push and Pop Directives Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/inline.md Illustrates how `push` and `pop` directives control the scope of inline options, specifically for ignoring a function call. ```lua -- luacheck: push ignore foo foo() -- No warning. -- luacheck: pop foo() -- Warning is emitted. ``` -------------------------------- ### Check Multiple Lua Strings with check_strings Source: https://context7.com/mpeterv/luacheck/llms.txt Validate multiple source strings simultaneously with global or per-source configuration options. ```lua local luacheck = require "luacheck" -- Check multiple source strings local sources = { "return foo", -- Warning: undefined global 'foo' "return math.floor(1)", -- OK (math is a standard global) "return return" -- Error: syntax error } -- Check without options (uses defaults) local report = luacheck.check_strings(sources) print("Warnings:", report.warnings) -- 1 print("Errors:", report.errors) -- 1 print("Fatals:", report.fatals) -- 0 -- Check with options local report_with_opts = luacheck.check_strings(sources, { std = "none", -- No standard globals ignore = {"113"} -- Ignore undefined global warnings }) -- Per-source options (index matches source position) local report_per_source = luacheck.check_strings(sources, { std = "lua53", -- Global option {std = "none"}, -- Options for sources[1] only {ignore = {"1"}}, -- Options for sources[2] only - ignore all globals {} -- Default options for sources[3] }) -- Iterate through file reports for i, file_report in ipairs(report) do if file_report.fatal then print(string.format("Source %d: Fatal error - %s", i, file_report.msg)) else for _, issue in ipairs(file_report) do print(string.format( "Source %d, Line %d: [%s] %s", i, issue.line, issue.code, issue.name or issue.msg )) end end end ``` -------------------------------- ### Configure Parallel Checking Source: https://context7.com/mpeterv/luacheck/llms.txt Run checks in parallel to speed up processing on multi-core systems. ```bash luacheck -j src/ luacheck -j 4 src/ luacheck --cache -j src/ ``` -------------------------------- ### CLI Option: --no-global Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/cli.md Documentation for the global variable filtering option in Luacheck. ```APIDOC ## --no-global ### Description Filter out warnings related to global variables. ### Method CLI Flag ### Parameters #### Options - **-g | --no-global** (flag) - Optional - Filter out warnings related to global variables. ``` -------------------------------- ### MIT License Text Source: https://github.com/mpeterv/luacheck/blob/master/README.md The full text of the MIT license governing the Luacheck project. ```text The MIT License (MIT) Copyright (c) 2014 - 2018 Peter Melnichenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -------------------------------- ### Trailing Whitespace Detection Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/warnings.md Illustrates code patterns where trailing whitespace is identified by Luacheck. ```lua -- Whitespace example. print("Hello") print("World") ``` -------------------------------- ### Unbalanced Assignment Exception Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/warnings.md Initializes multiple local variables to nil in a single statement to avoid unbalanced assignment warnings. ```lua local a, b, c = nil -- Effectively sets `a`, `b`, and `c` to nil, no warning. ``` -------------------------------- ### Define Custom Globals with Luacheck Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/config.md Use the 'std' option to define custom sets of globals. 'globals' can be set and accessed, while 'read_globals' can only be accessed. Globals can be defined by name or as tables with nested 'fields'. ```lua std = { globals = {"foo", "bar"}, -- these globals can be set and accessed. read_globals = {"baz", "quux"} -- these globals can only be accessed. } ``` ```lua std = { read_globals = { foo = { -- Defining read-only global `foo`... fields = { field1 = { -- `foo.field1` is now defined... fields = { nested_field = {} -- `foo.field1.nested_field` is now defined... } }, field2 = {} -- `foo.field2` is defined. } } } } ``` ```lua std = { read_globals = { foo = { -- `foo` and its fields are read-only by default (because they are within `read_globals` table). fields = { bar = { read_only = false, -- `foo.bar` is not read-only, can be set. other_fields = true, -- `foo.bar[anything]` is defined and can be set or mutated (inherited from `foo.bar`). fields = { baz = {read_only = true}, -- `foo.bar.baz` is read-only as an exception. } } } } } } ``` -------------------------------- ### Luacheck Module Functions Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/module.md This section details the core functions available in the Luacheck module for performing code analysis. ```APIDOC ## Luacheck Module API Use `local luacheck = require "luacheck"` to import the `luacheck` module. It contains the following functions: ### `luacheck.get_report(source)` **Description**: Given a source string, returns analysis data. **Parameters**: - **source** (string) - Required - The Lua source code string to analyze. **Returns**: - table - Analysis data for the provided source. ### `luacheck.process_reports(reports, options)` **Description**: Processes an array of analysis reports and applies options. Reports are processed sequentially, with later options overriding earlier ones. **Parameters**: - **reports** (table) - Required - An array of analysis reports. - **options** (table) - Optional - An array of option tables to apply to corresponding reports. **Returns**: - table - The final processed report. ### `luacheck.check_strings(sources, options)` **Description**: Checks an array of Lua source strings using the provided options and returns a final report. **Parameters**: - **sources** (table) - Required - An array of Lua source code strings. - **options** (table) - Optional - Options to apply during checking. **Returns**: - table - The final report after checking all sources. ### `luacheck.check_files(files, options)` **Description**: Checks an array of files using the provided options and returns a final report. File handles can be passed instead of filenames. **Parameters**: - **files** (table) - Required - An array of filenames or open file handles. - **options** (table) - Optional - Options to apply during checking. **Returns**: - table - The final report after checking all files. ### `luacheck.get_message(issue)` **Description**: Returns a string message for a given issue. **Parameters**: - **issue** (table) - Required - The issue table to format. **Returns**: - string - A human-readable message for the issue. ### `luacheck._VERSION` **Description**: Contains the Luacheck version as a string in `MAJOR.MINOR.PATCH` format. **Returns**: - string - The Luacheck version. ``` -------------------------------- ### Default Per-Path Standard Overrides Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/config.md Luacheck provides default per-path overrides for specific file patterns, such as test files and rockspec files, setting their 'std' value. ```lua files["**/spec/**/*_spec.lua"].std = "+busted" files["**/test/**/*_spec.lua"].std = "+busted" files["**/tests/**/*_spec.lua"].std = "+busted" files["**/*.rockspec"].std = "+rockspec" files["**/*.luacheckrc"].std = "+luacheckrc" ``` -------------------------------- ### Format Luacheck Output Source: https://context7.com/mpeterv/luacheck/llms.txt Adjust output verbosity and format for integration with external tools or CI systems. ```bash # Show warning codes in output luacheck --codes src/ # Show column ranges for warnings luacheck --ranges src/ # Suppress output for files without warnings luacheck --quiet src/ # Suppress warning details (only show summary per file) luacheck -qq src/ # Only show summary luacheck -qqq src/ # Disable colored output luacheck --no-color src/ # Use TAP (Test Anything Protocol) format luacheck --formatter TAP src/ # Use JUnit XML format for CI integration luacheck --formatter JUnit src/ # Use Visual Studio compatible format luacheck --formatter visual_studio src/ # Use plain format (one warning per line) luacheck --formatter plain src/ ``` -------------------------------- ### Convert issue tables to messages Source: https://context7.com/mpeterv/luacheck/llms.txt Use luacheck.get_message to transform structured issue tables into human-readable strings for logging or display. ```lua local luacheck = require "luacheck" -- Generate messages for different issue types local issues = { {code = "111", name = "foo", top = true}, {code = "113", name = "bar"}, {code = "211", name = "unused_func", func = true}, {code = "211", name = "recursive_fn", func = true, recursive = true}, {code = "212", name = "arg"}, {code = "311", name = "x"}, {code = "411", name = "var", prev_line = 5}, {code = "421", name = "shadowed", prev_line = 10}, {code = "521", label = "skip"}, {code = "011", msg = "expected '=' near 'foo'"}, {code = "561", function_type = "function", function_name = "complex_fn", complexity = 15, max_complexity = 10}, {code = "631", max_length = 120} } for _, issue in ipairs(issues) do print(string.format("[%s] %s", issue.code, luacheck.get_message(issue))) end -- Output: -- [111] setting non-standard global variable 'foo' -- [113] accessing undefined variable 'bar' -- [211] unused function 'unused_func' -- [211] unused recursive function 'recursive_fn' -- [212] unused argument 'arg' -- [311] value assigned to variable 'x' is unused -- [411] variable 'var' was previously defined on line 5 -- [421] shadowing definition of variable 'shadowed' on line 10 -- [521] unused label 'skip' -- [011] expected '=' near 'foo' -- [561] cyclomatic complexity of function 'complex_fn' is too high (15 > 10) -- [631] line is too long (120 max) ``` -------------------------------- ### luacheck.get_message API Source: https://context7.com/mpeterv/luacheck/llms.txt Converts an issue table into a human-readable message string. ```APIDOC ## luacheck.get_message API ### Description Converts an issue table into a human-readable message string. ### Method Not applicable (Lua function) ### Endpoint Not applicable (Lua function) ### Parameters #### Arguments - **issue** (table) - Required - A table representing an issue with various fields like code, name, func, etc. ### Request Example ```lua local luacheck = require "luacheck" local issues = { {code = "111", name = "foo", top = true}, {code = "113", name = "bar"}, {code = "211", name = "unused_func", func = true}, {code = "211", name = "recursive_fn", func = true, recursive = true}, {code = "212", name = "arg"}, {code = "311", name = "x"}, {code = "411", name = "var", prev_line = 5}, {code = "421", name = "shadowed", prev_line = 10}, {code = "521", label = "skip"}, {code = "011", msg = "expected '=' near 'foo'"}, {code = "561", function_type = "function", function_name = "complex_fn", complexity = 15, max_complexity = 10}, {code = "631", max_length = 120} } for _, issue in ipairs(issues) do print(string.format("[%s] %s", issue.code, luacheck.get_message(issue))) end ``` ### Response #### Success Response (string) - A human-readable message string describing the issue. #### Response Example ``` [111] setting non-standard global variable 'foo' [113] accessing undefined variable 'bar' [211] unused function 'unused_func' [211] unused recursive function 'recursive_fn' [212] unused argument 'arg' [311] value assigned to variable 'x' is unused [411] variable 'var' was previously defined on line 5 [421] shadowing definition of variable 'shadowed' on line 10 [521] unused label 'skip' [011] expected '=' near 'foo' [561] cyclomatic complexity of function 'complex_fn' is too high (15 > 10) [631] line is too long (120 max) ``` ``` -------------------------------- ### Filter Luacheck Warnings Source: https://context7.com/mpeterv/luacheck/llms.txt Apply CLI flags to suppress specific categories of warnings or ignore particular warning codes. ```bash # Disable global variable warnings luacheck --no-global src/ # Disable unused variable warnings luacheck --no-unused src/ # Disable redefined variable warnings luacheck --no-redefined src/ # Disable unused argument warnings luacheck --no-unused-args src/ # Disable unused secondary warnings luacheck --no-unused-secondaries src/ # Combine multiple filters luacheck --no-unused --no-redefined src/ # Ignore specific warning patterns (by code) luacheck --ignore 212 src/ # Ignore unused arguments # Ignore multiple patterns luacheck --ignore 212 --ignore 213 src/ # Only show specific warning types luacheck --only 1 src/ # Only global-related warnings # Enable specific warnings that were previously filtered luacheck --ignore 2 --enable 212 src/ ``` -------------------------------- ### Report Format Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/module.md Details the structure of the analysis reports generated by Luacheck. ```APIDOC ## 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 [List of warnings](warnings.md)), 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. | | 122, 142, 143 | `indirect` field indicates that the global field was accessed using a local alias. | | 122, 142, 143 | `field` field contains string representation of related global field. | | 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. | | 011 | `prev_line`, `prev_column`, and `prev_end_column` fields may point to an extra relevant location,
such as the opening unpaired bracket. | | 4.. | `prev_line`, `prev_column`, and `prev_end_column` fields contain location of the overwritten definition. | | 521 | `label` field contains label name. | | 631 | `line_ending` field contains `"comment"` or `"string"` if line ending is within a comment or a string. | | 631 | `max_length` field contains maximum allowed line length. | Other fields may be present for internal reasons. ``` -------------------------------- ### Detect Unused Local Variables and Uninitialized Variables Source: https://github.com/mpeterv/luacheck/blob/master/docsrc/warnings.md Luacheck warns about unused local variables (except '_') and detects variables that are set but never accessed, or accessed but never set. This snippet illustrates an unused value assigned to 'foo' and an uninitialized 'bar'. ```lua local foo = expr1() local bar if condition() then foo = expr2() bar = expr3() else foo = expr4() print(bar) end return foo, bar ```