Lua Cheat Sheet
Basics
// output, variables, strings
print("Hi", name); io.write("no newline")
local x = 5; local s = "a" .. "b"; local n = #s
local num = tonumber("42"); local str = tostring(42)
local v = cond and a or b
Control flow
if a then elseif b then else end
for i = 1, 10, 2 do end
for i, v in ipairs(arr) do end
for k, v in pairs(tbl) do end
while cond do end; repeat until cond
Tables
local t = {1, 2, 3}; t[#t + 1] = 4; table.insert(t, 1, 0); table.remove(t)
local d = {name = "Asha"}; d.age = 20; d["city"] = "Pune"; d.age = nil
table.sort(t, function(a, b) return a > b end); table.concat(t, ",")
Strings
s:upper(); s:lower(); s:sub(1, 3); s:len(); s:rep(3)
s:find("x"); s:match("%d+"); s:gsub("a", "b"); s:gmatch("%a+")
string.format("%s has %d points (%.1f%%)", name, n, pct)
Functions and OOP
local function f(a, b, ...) return a + b end
local Cls = {}; Cls.__index = Cls
function Cls.new(x) return setmetatable({x = x}, Cls) end
function Cls:get() return self.x end
Errors and coroutines
local ok, err = pcall(fn, arg)
error("message"); assert(x > 0, "x must be positive")
local co = coroutine.create(fn); coroutine.resume(co); coroutine.yield(v)
local M = require("module")
Full Lua documentation