๐ŸŒ™

Lua Cheat Sheet

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.

Jump to: Your first programVariablesif / else LoopsTablesFunctions ๐Ÿš€ Practice problems

Your first program

print("Hello, world!")
๐Ÿ“ Lua arrays are 1-indexed, not 0-indexed โ€” the first element is t[1], not t[0]. This trips up almost everyone coming from another language.

Variables

local age = 25
local name = "Sam"
local price = 19.99
๐Ÿ“ Always use local โ€” without it, a variable becomes global and can silently clash with other scripts.

if / else

local age = 20
if age >= 18 then
    print("Adult")
elseif age >= 13 then
    print("Teen")
else
    print("Child")
end

Loops

for i = 1, 5 do
    print(i)
end

local n = 3
while n > 0 do
    print(n)
    n = n - 1
end

Tables

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

Functions

local function add(a, b)
    return a + b
end

print(add(3, 4))

๐Ÿš€ Practice problems

Full runnable scripts, run in a real Lua sandbox โ€” same workspace as the other cheat sheets.

Sum a table EASY

local nums = {4, 8, 15, 16, 23, 42}
local sum = 0
for _, n in ipairs(nums) do
    sum = sum + n
end
print(sum)

Reverse a string MEDIUM

local function reverseStr(s)
    return s:reverse()
end

print(reverseStr("lua"))

FizzBuzz MEDIUM

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

Word frequency with a table HARD

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