Learn Stylua: The Essential Lua Code Formatter
Lua’s flexibility is a double-edged sword. While it offers freedom in coding style, inconsistencies can quickly creep into larger projects, making codebases harder to read, maintain, and collaborate on. Enter Stylua, the fast, robust, and reliable Lua code formatter that brings consistency and clarity to your projects. This article will dive deep into Stylua, covering its features, installation, usage, configuration, and integration with various tools.
What is Stylua?
Stylua is a command-line tool written in Rust that automatically formats Lua code according to a predefined (and customizable) style guide. It’s inspired by popular formatters like Prettier (JavaScript) and Black (Python), aiming to eliminate code style debates and enforce a uniform look across your entire project. Stylua rewrites your Lua code; it doesn’t just lint it. This means you save time manually formatting and can focus on the logic and functionality of your code.
Key Features:
- Speed: Built with Rust, Stylua is exceptionally fast, capable of formatting large codebases in seconds. This speed makes it practical to use within build processes and continuous integration pipelines.
- Robustness: Stylua handles a wide range of Lua syntax variations, including complex nested structures, metatables, and even (with limitations) code generation scenarios.
- Configuration: While Stylua offers sensible defaults, it’s highly configurable. You can customize various aspects of the formatting style, including indentation, line length, spacing, and more.
- Idempotency: Running Stylua multiple times on the same code produces the same output. This is crucial for consistent results and integration with version control systems.
- Error Recovery: Stylua strives to format as much of your code as possible, even if it encounters syntax errors. It will report errors, but often can still format the valid portions.
- Integration: Stylua integrates seamlessly with popular text editors (VS Code, Neovim, etc.), build tools (like Make), and CI/CD platforms (GitHub Actions, GitLab CI, etc.).
- Ignoring Files and Code Blocks: Stylua provides mechanisms to ignore specific files or sections of code that you don’t want formatted.
Installation:
Stylua offers several installation methods:
- Pre-built Binaries: The easiest way to install Stylua is to download a pre-built binary for your operating system (Windows, macOS, Linux) from the official GitHub releases page: https://github.com/JohnnyMorganz/StyLua/releases. Download the appropriate archive, extract it, and place the
stylua
executable in a directory within your system’sPATH
. - Cargo (Rust’s Package Manager): If you have Rust and Cargo installed, you can install Stylua using:
bash
cargo install stylua - Nix Package Manager:
bash
nix-env -iA nixpkgs.stylua - Homebrew (macOS):
bash
brew install stylua - LuaRocks:
bash
luarocks install --server=https://luarocks.org/dev stylua
Usage:
The basic command to format a Lua file is:
bash
stylua <file.lua>
This will print the formatted code to the standard output. To modify the file in-place, use the -w
or --write
flag:
bash
stylua -w <file.lua>
You can also format multiple files or entire directories:
bash
stylua src/ # Formats all Lua files in the 'src' directory and its subdirectories
stylua *.lua # Formats all Lua files in the current directory
To check if files are already formatted (without modifying them), use the --check
flag. This returns a non-zero exit code if any files need formatting, making it useful for CI/CD pipelines:
bash
stylua --check src/
Configuration:
Stylua uses a .stylua.toml
file in your project’s root directory (or specified using the --config-path
option) to define the formatting style. If no configuration file is found, Stylua uses its default style.
Here’s a sample .stylua.toml
file with explanations:
“`toml
.stylua.toml
Indentation style (spaces or tabs)
indent_type = “Spaces” # or “Tabs”
Number of spaces or tabs for indentation
indent_width = 4 # Common values: 2, 4
Maximum line length
line_width = 100
Whether to collapse empty parentheses in function calls
collapse_simple_statement = “Never” # Options: “Never”, “Always”, “FunctionCalls”
Alignment of table fields
alignment = “Preserve” # Options: “Preserve”, “None”
Spacing around operators
spaces_around_operators = true
Whether to remove trailing whitespace
trim_trailing_whitespace = true
Quote style for strings
quote_style = “AutoPreferDouble” # Options: “AutoPreferDouble”, “AutoPreferSingle”, “ForceDouble”, “ForceSingle”
Sort table keys when possible
sort_requires = true # options: true, false, “None”, “Alphanumeric”, “DeclarationOrder”
Whether to use trailing commas in tables
trailing_table_separator = “Never” # options: Never, Always, Smart
Spaces inside parentheses, brackets, and braces
[whitespace]
inside_parentheses = false
inside_brackets = false
before_comma = false
after_comma = true
End of line
[end_of_line]
end_of_line = “LF” # options: LF, CRLF, Auto
“`
The stylua.toml
file supports a wide variety of options. Refer to the official documentation (https://github.com/JohnnyMorganz/StyLua/blob/master/docs/configuration.md) for a complete list and detailed descriptions.
Ignoring Files and Code Blocks:
- Ignore Files: Create a
.styluaignore
file (similar to.gitignore
) in your project root. Each line in this file specifies a file or directory pattern to ignore. For example:
# .styluaignore
vendor/
generated_code.lua
*.min.lua
* Ignore Code Blocks: Use stylua: ignore start
and stylua: ignore end
comments to exclude specific sections of code from formatting:
“`lua
— stylua: ignore start
local matrix = {
{1, 0, 0},
{0, 1, 0},
{0, 0, 1}}
— stylua: ignore end
— The following will be formatted
local x = 1 + 2
``
stylua: ignore` at the end of the line.
* **Ignore a single line:** Use
lua
local test_var = get_something_very_long_name() -- stylua: ignore
Editor Integration:
- VS Code: Install the “StyLua” extension from the marketplace. It provides automatic formatting on save, formatting commands, and configuration options.
- Neovim: Stylua integrates well with Neovim’s built-in LSP client and formatters. You can use plugins like
null-ls.nvim
orconform.nvim
to configure Stylua as a formatter. Here’s an example usingconform.nvim
:
lua
-- conform.nvim configuration
require("conform").setup({
formatters_by_ft = {
lua = { "stylua" },
},
format_on_save = {
lsp_fallback = true,
timeout_ms = 500,
}
})
- Other Editors: Most editors with support for external formatters can be configured to use Stylua. Consult your editor’s documentation for details.
CI/CD Integration:
Stylua’s --check
flag is perfect for integrating with CI/CD pipelines. Here’s an example using GitHub Actions:
“`yaml
.github/workflows/ci.yml
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
lint:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v3
– name: Install Stylua
run: cargo install stylua
– name: Check Formatting
run: stylua –check src/
“`
This workflow will install Stylua and run stylua --check
on the src/
directory. If any files are not formatted according to the project’s configuration, the workflow will fail.
Conclusion:
Stylua is an invaluable tool for any Lua developer or team. It promotes consistency, improves readability, and reduces time spent on manual formatting. By adopting Stylua, you can focus on writing great code and let the formatter handle the rest. Its speed, configurability, and ease of integration make it the essential Lua code formatter. The detailed documentation and active community on GitHub ensure that Stylua is a well-supported and continuously improving tool.