Lua
Updated: September 10, 2025Categories: Languages, Gaming
Printed from:
Lua Cheatsheet
Language Overview
Lua is a lightweight, high-level programming language designed primarily for embedded scripting. Created in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes at the Pontifical Catholic University of Rio de Janeiro, Lua is known for its simplicity, efficiency, and powerful table-based data structure. It is widely used in game development (World of Warcraft, Roblox), game engines (LÖVE, Corona), embedded systems, and as a configuration language.
Key characteristics:
- Dynamically typed
- Garbage-collected
- Embeddable in C/C++
- Supports functional programming paradigms
- Lightweight and fast
- Extremely portable
Basic Syntax
lua
123456789101112131415161718-- Single line comment
--[[
Multi-line comment
supports multiple lines
]]
-- Print statement
print("Hello, World!")
-- Basic variable declaration
local x = 10
global_var = 20 -- Global variable (avoid when possible)
-- Function definition
function greet(name)
return "Hello, " .. name .. "!"
end
-- Calling a function
print(greet("Lua Developer"))
Data Types
lua
1234567891011121314-- Primitive Types
local nil_var = nil -- Represents absence of a value
local bool_true = true -- Boolean true
local bool_false = false -- Boolean false
local num_int = 42 -- Integer
local num_float = 3.14 -- Floating-point number
local str_simple = "Lua" -- String
-- Complex Types
local table_array = {1, 2, 3} -- Array-like table
local table_dict = {name = "Lua", version = 5.4} -- Dictionary-like table
local function_var = function() end -- Function as first-class value
local thread_var = coroutine.create(function() end) -- Coroutine thread
Variables and Constants
lua
1234567891011121314151617181920-- Local variables (recommended)
local x = 10
local y = 20
-- Global variables (use sparingly)
global_value = 30
-- Multiple variable assignment
local a, b, c = 1, 2, 3
-- Constants (use convention, no true constants)
local PI = 3.14159
local MAX_CONNECTIONS = 100
-- Scope demonstration
local function scope_demo()
local local_var = "I'm local" -- Function-level local
internal_var = "I'm global" -- Becomes global
end
Operators
lua
12345678910111213141516171819202122-- Arithmetic
local sum = 5 + 3 -- Addition
local diff = 10 - 4 -- Subtraction
local prod = 3 * 6 -- Multiplication
local div = 15 / 3 -- Division
local mod = 10 % 3 -- Modulo
local pow = 2 ^ 3 -- Exponentiation
-- Comparison
local is_equal = (5 == 5) -- Equality
local is_not_equal = (5 ~= 6) -- Inequality
local greater = (10 > 5) -- Greater than
local less_or_equal = (3 <= 4) -- Less than or equal
-- Logical
local and_op = true and false -- Logical AND
local or_op = true or false -- Logical OR
local not_op = not true -- Logical NOT
-- String Concatenation
local full_name = "Lua" .. " " .. "Programming"
Control Structures
lua
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849-- If-Else
local age = 20
if age < 18 then
print("Minor")
elseif age >= 18 and age < 65 then
print("Adult")
else
print("Senior")
end
-- For Loops
-- Numeric loop
for i = 1, 5 do
print(i) -- Prints 1, 2, 3, 4, 5
end
-- Reverse loop
for i = 5, 1, -1 do
print(i) -- Prints 5, 4, 3, 2, 1
end
-- Generic loop (iterate over tables)
local fruits = {"apple", "banana", "cherry"}
for index, fruit in ipairs(fruits) do
print(index, fruit)
end
-- While Loop
local count = 0
while count < 5 do
print(count)
count = count + 1
end
-- Repeat-Until Loop
local x = 0
repeat
x = x + 1
print(x)
until x >= 5
-- Break and Continue
for i = 1, 10 do
if i == 3 then
break -- Exit loop
end
print(i)
end
Functions
lua
1234567891011121314151617181920212223242526272829303132333435-- Simple function
function add(a, b)
return a + b
end
-- Function with multiple return values
function get_person_details()
return "John", 30, "Engineer"
end
-- Anonymous/Lambda functions
local multiply = function(a, b) return a * b end
-- Closures
function counter()
local count = 0
return function()
count = count + 1
return count
end
end
local increment = counter()
print(increment()) -- 1
print(increment()) -- 2
-- Variadic functions
function sum(...)
local total = 0
for _, v in ipairs({...}) do
total = total + v
end
return total
end
print(sum(1, 2, 3, 4)) -- 10
Data Structures
lua
12345678910111213141516171819202122-- Tables as Arrays
local fruits = {"apple", "banana", "cherry"}
print(fruits[1]) -- "apple" (1-based indexing)
table.insert(fruits, "date")
table.remove(fruits, 2)
-- Tables as Dictionaries
local person = {
name = "John",
age = 30,
city = "New York"
}
print(person.name)
person.job = "Developer"
-- Mixed Tables
local mixed = {
42,
name = "Mixed Table",
[true] = "Boolean key"
}
Object-Oriented Programming
lua
1234567891011121314151617181920212223242526272829303132333435-- Metatable-based OOP
local Person = {}
Person.__index = Person
function Person.new(name, age)
local self = setmetatable({}, Person)
self.name = name
self.age = age
return self
end
function Person:introduce()
print("Hi, I'm " .. self.name)
end
local john = Person.new("John", 30)
john:introduce()
-- Inheritance
local Student = setmetatable({}, {__index = Person})
function Student.new(name, age, grade)
local self = Person.new(name, age)
setmetatable(self, Student)
self.grade = grade
return self
end
function Student:study()
print(self.name .. " is studying")
end
local jane = Student.new("Jane", 25, 12)
jane:introduce() -- Inherited method
jane:study() -- Student's method
Error Handling
lua
123456789101112131415161718192021222324-- Protected Call
local function divide(a, b)
if b == 0 then
error("Cannot divide by zero")
end
return a / b
end
local status, result = pcall(divide, 10, 2)
print(status, result) -- true, 5
local status, err = pcall(divide, 10, 0)
print(status, err) -- false, error message
-- Custom Error Handling
local function custom_error_handler(err)
print("Custom error handler: " .. err)
return err
end
xpcall(function()
error("Something went wrong")
end, custom_error_handler)
File I/O
lua
12345678910111213141516-- Writing to a file
local file = io.open("example.txt", "w")
file:write("Hello, Lua!")
file:close()
-- Reading from a file
local file = io.open("example.txt", "r")
local content = file:read("*all")
print(content)
file:close()
-- Iterating through file lines
for line in io.lines("example.txt") do
print(line)
end
Common Libraries and Frameworks
-
Standard Libraries:
math: Mathematical functionsstring: String manipulationtable: Table operationsio: Input/Output operationsos: Operating system interactionscoroutine: Cooperative multitasking
-
Popular External Libraries:
- LuaSocket: Networking
- Luasec: SSL support
- Ltn12: Filters and pumps
- Lua Lanes: Multithreading
- LuaUnit: Unit testing
- Lapis: Web framework
Best Practices
- Prefer local variables
- Use meaningful variable names
- Leverage metatables for advanced programming
- Be mindful of memory usage
- Use
require()for modular code - Avoid global variables
- Use
pairs()andipairs()correctly - Understand 1-based indexing
- Use coroutines for cooperative multitasking
- Profile and optimize performance-critical code
Testing
lua
12345678910111213-- Using LuaUnit
local lu = require("luaunit")
function test_addition()
lu.assertEquals(1 + 1, 2)
end
function test_string_concat()
lu.assertEquals("Hello" .. " World", "Hello World")
end
os.exit(lu.LuaUnit.run())
Resources for Further Learning
- Official Lua Documentation: https://www.lua.org/docs.html
- Programming in Lua (book) by Roberto Ierusalimschy
- Lua Users Wiki: http://lua-users.org/wiki/
- LÖVE Game Framework: https://love2d.org/
- Lua Workshop Proceedings
- LuaRocks Package Manager
Tips and Tricks
- Use
collectgarbage()for manual garbage collection - Utilize
debuglibrary for advanced introspection - Embed Lua in C/C++ projects
- Use Lua for configuration and scripting
- Explore domain-specific Lua implementations
Continue Learning
Discover more cheatsheets to boost your productivity