Lua Reference
0. Basics
0.1 Hello World
-- print() adds a newline by default
print("Hello, World!")Hello, World!
0.2 Building & Running
Lua is an interpreted scripting language. Use the
lua command to execute scripts.
# Run a Lua script directly
lua script.luaHello, World!
0.3 Comments
-- Single-line comment
--[[
Multi-line
comment block
--]](No output)
0.4 Imports
Lua uses require to load modules.
local math = require("math") -- Standard math library
local socket = require("socket") -- Common external library(No output)
0.5 Exit Codes
-- os.exit(code, [close])
-- 0 for success, non-zero for error
os.exit(1)(Process exits with status 1)
0.6 Error Handling
-- pcall (protected call) catches errors
local status, err = pcall(function()
error("Something went wrong")
end)
if not status then
print("Caught error: " .. err)
end
-- assert throws error if condition is false
assert(1 == 1, "This will not throw")Caught error: [string "local status, err = pcall(function()..."]:2: Something went wrong
1. Environment & Time
1.1 Variable Declaration
Variables are global by default; local is
preferred for scoping.
local x = 10 -- Local variable
y = 20 -- Global variable
local name = "Lua" -- String(No output)
1.2 Integer Types
Lua 5.3+ supports integers; earlier versions use doubles for all numbers.
local int_val = 100
local float_val = 3.14
print(type(int_val))number
1.3 Casting
Explicit conversion using tonumber and
tostring.
local n = tonumber("123") -- String to number (123)
local s = tostring(456) -- Number to string ("456")
local f = tonumber("invalid") -- nil(No output)
1.4 Truthiness
In Lua, only false and nil are
falsy. 0 and "" (empty string) are
truthy.
if 0 then
print("0 is true")
end
if "" then
print("Empty string is true")
end0 is true
Empty string is true
1.5 Environment Vars
local path = os.getenv("PATH")
print(path ~= nil)true
1.6 Time
local seconds = os.time() -- Current time in seconds
local date_str = os.date("%Y-%m-%d %H:%M:%S") -- Formatted date
local cpu_time = os.clock() -- CPU time for performance measurement
print(date_str)2024-05-16 12:00:00 (example)
2. Operators & Regex
2.1 Arithmetic/Logic
local add = 10 + 5
local floor_div = 10 // 3 -- Lua 5.3+ floor division
local power = 2 ^ 10 -- 1024
local neq = 10 ~= 5 -- Not equal
local logic = true and false or true -- and/or/not(No output)
2.2 Regex
Lua uses “patterns” (similar to regex but simpler).
local text = "The price is $100"
-- string.match returns captures
local price = string.match(text, "%$(%d+)")
print(price)100
3. Argument Parsing
3.1 CLI Argument Parsing
Command-line arguments are stored in the global
arg table.
-- arg[0] is the script name, arg[1] is the first argument
for i = 1, #arg do
print("Arg " .. i .. ": " .. arg[i])
end(Depends on CLI input)
4. Functions & Memory
4.1 Declaration/Returns
local function add(a, b)
return a + b
end
-- Multiple returns
local function swap(a, b)
return b, a
end
local x, y = swap(10, 20)(No output)
4.2 References/Pointers
Tables are the only data structure and are passed by reference. Metatables allow operator overloading and OO.
local t1 = {val = 1}
local t2 = t1 -- t2 points to same table as t1
t2.val = 2
print(t1.val)
-- Metatable example
local mt = { __add = function(a, b) return a.x + b.x end }
local obj = {x = 10}
setmetatable(obj, mt)2
5. Loops & Iteration
5.1 Basic Loops
-- While loop
local i = 1
while i <= 3 do
print("while: " .. i)
i = i + 1
end
-- Numeric for loop (start, stop, step)
for j = 1, 3 do
print("for: " .. j)
endwhile: 1
while: 2
while: 3
for: 1
for: 2
for: 3
5.2 Break/Continue
Lua supports break. Standard Lua
(pre-5.2/JIT) lacks continue.
for i = 1, 10 do
if i > 2 then break end
print(i)
end1
2
5.3 Iterating Collections
local list = {"a", "b", "c"}
-- ipairs for array-like tables
for i, v in ipairs(list) do
print(i, v)
end
local map = {key = "val"}
-- pairs for all keys
for k, v in pairs(map) do
print(k, v)
end1 a
2 b
3 c
key val
6. Strings & Files
6.1 Manipulation
local s = "hello"
local upper = s:upper() -- "HELLO"
local sub = s:sub(1, 2) -- "he" (1-indexed)
local concat = "a" .. "b" -- "ab"
local len = #s -- 5(No output)
6.2 Path Joining
Lua has no built-in path join; usually implemented manually.
local function join(path, file)
local sep = package.config:sub(1, 1)
return path .. sep .. file
end
print(join("/usr", "bin"))/usr/bin (on Unix)
6.3 Streaming I/O
local f = io.open("test.txt", "w")
if f then
f:write("line 1\n")
f:write("line 2\n")
f:close()
end(No output)
6.4 Read to Memory
local f = io.open("test.txt", "r")
if f then
local content = f:read("*a") -- "*a" reads the entire file
f:close()
print(content)
endline 1
line 2
7. Binary & Bitwise
7.1 Allocation/Packing
Lua 5.3+ provides string.pack and
string.unpack.
-- pack(format, values...)
-- ">i4" is Big-endian 4-byte integer
local binary_data = string.pack(">i4d", 42, 3.14)
local val, pi = string.unpack(">i4d", binary_data)(No output)
7.2 Bitwise Ops
Lua 5.3+ supports bitwise operators directly.
local and_res = 0x0F & 0xF0 -- 0
local or_res = 0x0F | 0xF0 -- 255
local lshift = 1 << 3 -- 8
local not_res = ~0 -- -1 (signed)(No output)
7.3 Hex Conversion
local hex_str = string.format("%02x", 255) -- "ff"
local num = tonumber("ff", 16) -- 255(No output)
8. Collections & JSON
8.1 Lists/Maps/Sets (Tables)
Tables serve all purposes.
local list = {10, 20}
table.insert(list, 30)
local map = {a = 1, b = 2}
map["c"] = 3
local set = {["item1"] = true, ["item2"] = true}
print(set["item1"])true
8.2 JSON Parsing
Commonly uses lua-cjson or
dkjson.
local cjson = require("cjson")
local json_text = '{"id": 42, "name": "lua"}'
local data = cjson.decode(json_text)
print(data.name)
local encoded = cjson.encode({status = "ok"})lua
9. Systems & Networking
9.1 TCP
Using luasocket.
local socket = require("socket")
local client = socket.connect("example.com", 80)
client:send("GET / HTTP/1.0\r\n\r\n")
local line, err = client:receive()
client:close()(No output)
9.2 UDP
local socket = require("socket")
local udp = socket.udp()
udp:setpeername("127.0.0.1", 12345)
udp:send("hello")
udp:close()(No output)
9.3 Concurrency (Coroutines)
Lua uses cooperative multitasking via coroutines.
local co = coroutine.create(function()
print("Coroutine started")
coroutine.yield("yielded value")
print("Coroutine resumed")
end)
local status, res = coroutine.resume(co)
print(res)
coroutine.resume(co)Coroutine started
yielded value
Coroutine resumed
9.4 SQLite
Using lsqlite3.
local sqlite3 = require("lsqlite3")
local db = sqlite3.open_memory()
db:exec[[
CREATE TABLE test (id INTEGER, content TEXT);
INSERT INTO test VALUES (1, 'Hello World');
]]
for row in db:nrows("SELECT * FROM test") do
print(row.id, row.content)
end
db:close()1 Hello World