Lua is a powerful, efficient, lightweight, embeddable scripting language designed for extending applications.
Basic Syntax
Comments
-- Single-line comment
--[[
Multi-line comment
spans multiple lines
--]]
Function Call Shorthand
Parentheses can be omitted when a function receives exactly one string literal or table constructor:
print("Hello World") <==> print "Hello World"
dofile('app.lua') <==> dofile 'app.lua'
config({ x = 1 }) <==> config{ x = 1 }
Tables & Arrays
Tables are Lua's sole data-structuring mechanism. Arrays use 1-based indexing:
-- Empty table
local t = {}
-- Key-value table (dictionary)
local user = { name = "Alice", age = 30 }
user.role = "admin"
user["email"] = "[email protected]"
-- Sequential array (1-based index)
local fruits = { "apple", "banana", "cherry" }
print(fruits[1]) -- prints "apple"
print(#fruits) -- length operator (3)
Control Flow & Loops
Conditionals
Only false and nil are falsy in Lua. 0 and "" are truthy:
if score >= 90 then
grade = "A"
elseif score >= 80 then
grade = "B"
else
grade = "C"
end
Loops
-- While loop
local count = 1
while count <= 5 do
count = count + 1
end
-- Repeat...until loop (runs at least once)
repeat
count = count - 1
until count == 0
-- Numeric for loop: for var = start, stop [, step]
for i = 1, 10, 2 do
print(i) -- 1, 3, 5, 7, 9
end
-- Generic for loop: ipairs (array) and pairs (dictionary)
for index, value in ipairs(fruits) do
print(index, value)
end
for key, value in pairs(user) do
print(key, value)
end
Functions
Definitions & Multiple Return Values
-- Multiple returns
local function min_max(a, b)
if a < b then
return a, b
else
return b, a
end
end
local minimum, maximum = min_max(10, 5)
-- Variable arguments (varargs)
local function sum(...)
local s = 0
for _, v in ipairs({...}) do
s = s + v
end
return s
end
Metatables & Object-Oriented Programming
Metatables & Metamethods
local Vector = {}
Vector.__index = Vector
function Vector.new(x, y)
local instance = setmetatable({}, Vector)
instance.x = x
instance.y = y
return instance
end
-- Vector addition metamethod
function Vector.__add(a, b)
return Vector.new(a.x + b.x, a.y + b.y)
end
function Vector:__tostring()
return string.format("(%d, %d)", self.x, self.y)
end
local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
local v3 = v1 + v2
print(v3) -- "(4, 6)"
Metamethod Reference
| Metamethod | Trigger Event |
|---|---|
__index |
Reading a non-existent field (t[k]) |
__newindex |
Assigning to a non-existent field (t[k] = v) |
__tostring |
String conversion (tostring(t)) |
__call |
Calling the table like a function (t()) |
__add, __sub |
Addition (+), subtraction (-) |
__mul, __div |
Multiplication (*), division (/) |
__eq, __lt, __le |
Comparison (==, <, <=) |
__concat |
Concatenation (..) |
Standard Library APIs
String Functions
string.len("hello") -- 5 (#"hello" also works)
string.lower("HELLO") -- "hello"
string.upper("hello") -- "HELLO"
string.sub("hello", 2, 4) -- "ell"
string.format("%s = %d", "x", 5)-- "x = 5"
string.gsub("banana", "a", "o") -- "bonono"
string.find("hello world", "wor") -- 7, 9
Table Functions
table.insert(fruits, "orange") -- Append
table.insert(fruits, 1, "grape") -- Insert at index 1
table.remove(fruits, 1) -- Remove first item
table.concat(fruits, ", ") -- Join strings: "apple, banana"
table.sort(fruits) -- Sort array in-place
Math Functions
math.abs(-10) -- 10
math.floor(3.7) -- 3
math.ceil(3.2) -- 4
math.max(1, 9, 4) -- 9
math.random(1, 100) -- Random integer between 1 and 100