Lua Comments
Comments are notes for humans. Lua ignores them completely. They explain why code does something, document functions, and temporarily switch code off while you debug.
Single-line comments
Two hyphens -- start a comment that runs to the end of the line:
-- Compute the area of a circle
local radius = 3
local area = math.pi * radius ^ 2 -- ^ is exponentiation
print(area)28.274333882308
Multi-line comments
A block comment starts with --[[ and ends with ]]:
--[[
This program prints a greeting.
Author: the TAD team
Nothing here is executed.
]]
print("Greetings!")Greetings!
If the comment itself contains ]] (for example, code that indexes a nested table: a[b[1]]), use the "level" form with equals signs. --[==[ is closed only by ]==], with the same number of =:
--[==[
local value = matrix[row[1]]
The ]] above does not end this comment.
]==]
print("still running")still running
A handy trick: toggling a block
Many Lua programmers write block comments like this:
--[[
print("debug output")
--]]The closing line --]] is itself a comment when the block is active. To switch the code back on, add one hyphen to the first line: ---[[ turns the opening into a plain single-line comment, and the lines between run again:
---[[
print("this line now runs")
--]]
print("done")this line now runs
done
Documentation comments
Lua itself has no doc-comment syntax, but tools do. The Lua Language Server (used by VS Code and Neovim) reads LuaCATS annotations, which start with three hyphens:
---Returns the price after a percentage discount.
---@param price number the original price
---@param percent number the discount, 0-100
---@return number
local function discounted(price, percent)
return price * (1 - percent / 100)
end
print(discounted(80, 25))60.0
The editor shows these as hover text and uses the types to warn you about mistakes. To Lua they are ordinary comments.
Tip: Good comments explain intent and surprises ("prices are stored in cents to avoid rounding errors"), not what the code obviously does ("add 1 to i").
Common mistakes
| Mistake | What happens |
|---|---|
// comment (C style) |
syntax error: // is floor division in Lua |
# comment (shell style) |
syntax error, except on the very first line of a file (#!/usr/bin/env lua is allowed there) |
forgetting ]] |
everything after --[[ becomes a comment |
Test yourself
Which line is a valid Lua comment?
// total# total-- total/* total */
How do you start a multi-line comment?
--[[/*---<!--
What does ---[[ at the start of a commented block do?
- Starts a doc comment block
- Makes the opening a normal one-line comment, so the block's code runs
- Causes a syntax error
- Comments out the whole file