A tiny, fast language built to be embedded inside other programs โ it's the scripting layer behind Roblox, World of Warcraft addons, Neovim config, and countless game engines. Copy-paste examples plus live Run/Submit exercises.
print("Hello, world!")
t[1], not t[0]. This trips up almost everyone coming from another language.local age = 25
local name = "Sam"
local price = 19.99
local โ without it, a variable becomes global and can silently clash with other scripts.local age = 20
if age >= 18 then
print("Adult")
elseif age >= 13 then
print("Teen")
else
print("Child")
end
for i = 1, 5 do
print(i)
end
local n = 3
while n > 0 do
print(n)
n = n - 1
end
Lua has exactly one data structure โ the table โ used as both an array and a dictionary.
local nums = {10, 20, 30}
table.insert(nums, 40)
print(nums[1]) -- 10 (1-indexed!)
print(#nums) -- 4 (# gives length)
local ages = { Sam = 25, Ana = 30 }
print(ages.Sam) -- 25
ages.Lee = 40
local function add(a, b)
return a + b
end
print(add(3, 4))
Full runnable scripts, run in a real Lua sandbox โ same workspace as the other cheat sheets.
local nums = {4, 8, 15, 16, 23, 42}
local sum = 0
for _, n in ipairs(nums) do
sum = sum + n
end
print(sum)
local function reverseStr(s)
return s:reverse()
end
print(reverseStr("lua"))
for i = 1, 15 do
if i % 15 == 0 then
print("FizzBuzz")
elseif i % 3 == 0 then
print("Fizz")
elseif i % 5 == 0 then
print("Buzz")
else
print(i)
end
end
local text = "the cat sat on the mat the cat ran"
local counts = {}
for word in text:gmatch("%a+") do
counts[word] = (counts[word] or 0) + 1
end
for word, n in pairs(counts) do
print(word .. ": " .. n)
end