Lua Code Formatter

For Neovim configs that grew by copy and paste, Redis scripts squeezed onto one line for EVAL, and addons nobody has reindented in years. StyLua, compiled to WebAssembly, rewrites the file with consistent layout and points parse errors at a line and column.

Input

Settings

History

Load from URL

Lua code and StyLua

Lua turns up wherever a program needs a small embedded scripting language: Neovim and WezTerm configuration, LÖVE and Defold games, Roblox, World of Warcraft addons, Redis EVAL scripts, Nginx through OpenResty, and HAProxy. Its syntax is loose enough that hand-written files drift quickly, with statements packed onto one line, mixed quote styles and inconsistent indentation.

StyLua is an opinionated Lua formatter written in Rust and modelled on Prettier: it parses the file and prints it again from the syntax tree, so the result is the same however messy the input was. It is especially common among Neovim plugin authors, and many plugin repositories check formatting with it in CI. Here it runs as WebAssembly inside the page; your scripts are never sent to a server.

What StyLua changes

  • One statement per line. local a=1 local b=2 becomes two lines, and if not ok then return end is expanded into a three-line block.
  • Spacing. Spaces go around operators and after commas, and table constructors get padding: {a=1} becomes { a = 1 }.
  • Quotes. Strings prefer double quotes, so 'hello' becomes "hello". A string that would need escapes keeps the quote that avoids them, so 'say "hi"' is left alone. Long bracket strings like [[ ... ]] are never touched.
  • Call parentheses. Lua lets you call a function with a single string or table argument and no parentheses. StyLua adds them, so require 'socket' becomes require("socket") and setup{...} becomes setup({...}).
  • Line wrapping. Long calls and tables are broken over several lines at 80 columns. Anonymous functions passed as arguments, such as the callback in vim.keymap.set, keep the function() on the call line and close with end, {...}).

Comments are kept in place and require calls stay in the order you wrote them. To protect a hand-aligned table, put -- stylua: ignore on the line before a statement, or wrap a region in -- stylua: ignore start and -- stylua: ignore end.

Pasting code from each host

Redis. Paste the Lua body rather than the whole redis-cli command, whose shell quoting is not Lua. Multi-line scripts work fine with EVAL, so there is no need to keep the one-line version in your repository, and a formatted script is far easier to review when it guards a rate limit or a lock. KEYS and ARGV are ordinary globals as far as the parser is concerned.

Neovim. A lazy.nvim plugin spec is a return of a table, and it formats like any other. Match the 2-space indent most configs use.

OpenResty and addons. Formatting does not need the host’s APIs, so ngx.* and CreateFrame are just names. That also means nothing here checks that a function exists: attempt to index a nil value still appears at run time.

Indentation and language versions

There are no Lua-specific options. The toolbar’s Indent decides between 2 spaces, 4 spaces and tabs. StyLua’s own default is tabs, so match whatever the rest of your repository uses. Lines are wrapped at 80 columns rather than StyLua’s usual 120, and StyLua treats that width as a target rather than a hard cap, so an unbreakable long string can still run past it. StyLua runs on Ctrl/Cmd+Enter, and Ctrl/Cmd+Shift+C copies.

The parser accepts Lua 5.1 through 5.4, which covers LuaJIT as well: goto and ::labels::, integer division //, bitwise operators and <const> and <close> attributes all work. Luau, the Roblox dialect, is only partly supported. A .luau file formats if it sticks to standard Lua, but type annotations such as a: number, type declarations, continue and compound assignments like x += 1 fail with a parse error.

Examples

Neovim plugin spec for lazy.nvim

The spec table spreads over several lines, single quotes become double, and the setup call stays attached to its config function.

Input
return {'nvim-treesitter/nvim-treesitter',build=':TSUpdate',event={'BufReadPost','BufNewFile'},config=function() require('nvim-treesitter.configs').setup({ensure_installed={'lua','vim','vimdoc','query'},highlight={enable=true},indent={enable=true}}) end}
Output
return {
  "nvim-treesitter/nvim-treesitter",
  build = ":TSUpdate",
  event = { "BufReadPost", "BufNewFile" },
  config = function()
    require("nvim-treesitter.configs").setup({
      ensure_installed = { "lua", "vim", "vimdoc", "query" },
      highlight = { enable = true },
      indent = { enable = true },
    })
  end,
}
Open this example in the tool

Redis rate limiter written for EVAL

A one-line script becomes separate statements, so the first-request EXPIRE and the limit check can be reviewed as two distinct steps.

Input
local current=redis.call('INCR',KEYS[1]) if current==1 then redis.call('EXPIRE',KEYS[1],ARGV[1]) end if current>tonumber(ARGV[2]) then return redis.error_reply('rate limited') end return current
Output
local current = redis.call("INCR", KEYS[1])
if current == 1 then
  redis.call("EXPIRE", KEYS[1], ARGV[1])
end
if current > tonumber(ARGV[2]) then
  return redis.error_reply("rate limited")
end
return current
Open this example in the tool

OpenResty access check with call shorthand

The parenthesis-free require gains parentheses, while strings containing double quotes keep their single quotes so nothing needs escaping.

Input
local auth_header=ngx.var.http_authorization if not auth_header then ngx.status=ngx.HTTP_UNAUTHORIZED ngx.header['WWW-Authenticate']='Bearer realm="api"' ngx.say('{"error":"missing token"}') return ngx.exit(ngx.HTTP_UNAUTHORIZED) end
local lim,err=require'resty.limit.req'.new('limit_store',10,5) if not lim then ngx.log(ngx.ERR,'limiter init failed: ',err) end
Output
local auth_header = ngx.var.http_authorization
if not auth_header then
  ngx.status = ngx.HTTP_UNAUTHORIZED
  ngx.header["WWW-Authenticate"] = 'Bearer realm="api"'
  ngx.say('{"error":"missing token"}')
  return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
local lim, err = require("resty.limit.req").new("limit_store", 10, 5)
if not lim then
  ngx.log(ngx.ERR, "limiter init failed: ", err)
end
Open this example in the tool

World of Warcraft event handler

The nested if and elseif branches are indented with tabs, the anonymous handler stays on the SetScript line, and the varargs and multiple assignment are spaced evenly.

Input
local addon=CreateFrame('Frame') addon:RegisterEvent('PLAYER_LOGIN') addon:RegisterEvent('COMBAT_LOG_EVENT_UNFILTERED')
addon:SetScript('OnEvent',function(self,event,...) if event=='PLAYER_LOGIN' then print('|cff00ff00Tracker loaded|r') elseif event=='COMBAT_LOG_EVENT_UNFILTERED' then local _,subevent,_,_,sourceName=CombatLogGetCurrentEventInfo() if subevent=='SPELL_CAST_SUCCESS' then counts[sourceName]=(counts[sourceName] or 0)+1 end end end)
Output
local addon = CreateFrame("Frame")
addon:RegisterEvent("PLAYER_LOGIN")
addon:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
addon:SetScript("OnEvent", function(self, event, ...)
	if event == "PLAYER_LOGIN" then
		print("|cff00ff00Tracker loaded|r")
	elseif event == "COMBAT_LOG_EVENT_UNFILTERED" then
		local _, subevent, _, _, sourceName = CombatLogGetCurrentEventInfo()
		if subevent == "SPELL_CAST_SUCCESS" then
			counts[sourceName] = (counts[sourceName] or 0) + 1
		end
	end
end)
Open this example in the tool

Common errors and how to fix them

ErrorCauseFix
error parsing: unexpected token `` (1:20 to 1:27), expected `end` to close function body blockA function has no closing end. The empty token in the message is the end of the input.Add end after the last statement of the function. Counting function, if, for and while openers against end keywords helps find which one is missing.
error parsing: unexpected token `` (1:19 to 1:19), expected `end` to conclude `if`An if … then block was never closed with end.Add end after the last statement of the if block.
error parsing: unclosed string (1:11 to 1:15)A quoted string is missing its closing quote. Regular Lua strings cannot span lines.Close the quote, or use a long bracket string [[ … ]] for text with line breaks.
error parsing: unexpected token `+` (1:13 to 1:14), expected expression after binary operatorAn expression ends with an operator and nothing after it, often from a line that was cut off.Finish the expression or remove the trailing operator.
error parsing:Some mistakes produce the bare prefix with only a position: a doubled comma in a table, a missing then or do, != instead of Lua’s ~=, = in place of ==, or Luau syntax such as x += 1.Look at the highlighted column and read the token there. If the code is Luau, the error is expected: only standard Lua syntax is supported.
ERR Error compiling script (new function): user_script:3: 'end' expected (to close 'function' at line 1) near '<eof>'Reported by Redis, not by this page: Lua inside Redis could not compile the script. Redis counts lines from the start of the script you sent.Paste the script here to see the block structure and the position of the problem. The same missing end appears above with StyLua’s wording.

Frequently asked questions

Is the output identical to running stylua locally?

It matches StyLua with default settings except for two values taken from the page: the toolbar indentation and an 80-column width instead of StyLua’s 120. Set your stylua.toml to the same values for identical results.

Can I format Roblox Luau code?

Only the parts that are plain Lua. Type annotations, type aliases, continue and compound assignment operators are Luau extensions and fail to parse here.

Why were parentheses added to my require calls?

StyLua always writes call parentheses by default, turning require ‘x’ into require(“x”). Both forms do the same thing in Lua.

How do I keep a table aligned by hand?

Put – stylua: ignore on the line above the statement, or surround a section with – stylua: ignore start and – stylua: ignore end.

Does it work with LuaJIT and OpenResty code?

Yes. LuaJIT uses Lua 5.1 syntax with a few 5.2 additions such as goto, all of which the parser accepts.

Can I format a Redis EVAL script without changing how it runs?

Yes, as long as you paste only the Lua body. Formatting changes layout and quote style, and Redis accepts multi-line scripts, so the formatted version behaves the same.

Related tools