Lua Cheat Sheet
Lua is a lightweight, embeddable scripting language widely used in game development, embedded systems, and configuration environments. This Lua cheatsheet is a structured, example-driven reference covering core syntax, tables, functions, metatables, and coroutine-based concurrency.
Basic Program
print("Hello, Lua")
Variables
a = 10
b = "text"
c = true
local x = 5
Data Types
number
string
boolean
table
function
userdata
thread
nil
type(10)
type("lua")
Strings
s = "Lua"
s:upper()
s:lower()
string.len(s)
name = "World"
print("Hello " .. name)
print(string.format("Hello %s", name))
Operators
a + b
a - b
a * b
a / b
a % b
a ^ b
a == b
a ~= b
a > b
a < b
a and b
a or b
not a
Control Flow
if / elseif / else
if x > 10 then
print("large")
elseif x > 5 then
print("medium")
else
print("small")
end
while
while x > 0 do
x = x - 1
end
repeat / until
repeat
x = x - 1
until x == 0
for
for i = 1, 5 do
print(i)
end
for i = 1, 10, 2 do
print(i)
end
Functions
function add(a, b)
return a + b
end
result = add(2, 3)
Anonymous Functions
square = function(x)
return x * x
end
Multiple Return Values
function divide(a, b)
return a / b, a % b
end
q, r = divide(10, 3)
Tables
t = {1, 2, 3}
person = {
name = "A",
age = 20
}
Table Access
t[1]
person.name
person["age"]
Table Iteration
for i, v in ipairs(t) do
print(i, v)
end
for k, v in pairs(person) do
print(k, v)
end
Table Functions
table.insert(t, 4)
table.remove(t, 1)
table.sort(t)
Tables as Objects
Counter = {
value = 0
}
function Counter:increment()
self.value = self.value + 1
end
Counter:increment()
Metatables
mt = {}
function mt.__add(a, b)
return { a[1] + b[1] }
end
setmetatable({1}, mt) + {2}
__index Metamethod
proto = {
greet = function(self)
print("hello")
end
}
obj = {}
setmetatable(obj, { __index = proto })
obj:greet()
Modules
-- math_utils.lua
local M = {}
function M.add(a, b)
return a + b
end
return M
local math_utils = require("math_utils")
math_utils.add(2, 3)
Coroutines
co = coroutine.create(function()
print("start")
coroutine.yield()
print("end")
end)
coroutine.resume(co)
coroutine.resume(co)
Coroutine Status
coroutine.status(co)
Error Handling
error("failed")
status, err = pcall(function()
error("fail")
end)
File I/O
file = io.open("file.txt", "w")
file:write("text")
file:close()
file = io.open("file.txt", "r")
content = file:read("*a")
file:close()
Environment Variables
os.getenv("PATH")
Command Line Arguments
for i, v in ipairs(arg) do
print(i, v)
end
Time & Date
os.time()
os.date("%Y-%m-%d")