Introduction to Lua
Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.
What is Lua?
Lua is designed, implemented, and maintained by a team at PUC-Rio, the Pontifical Catholic University of Rio de Janeiro in Brazil. Lua was born and raised in academia but has gradually moved toward industrial applications.
Key Features
- Lightweight: Small memory footprint
- Fast: Excellent performance for a scripting language
- Portable: Runs on virtually any platform
- Embeddable: Easy to integrate with other languages
- Simple: Clean syntax and powerful semantics
Hello World
print("Hello, World!")
Basic Syntax
Lua has a simple and clean syntax. Here are the fundamental elements:
Comments
-- This is a single-line comment
--[[
This is a
multi-line comment
--]]
Statements
Statements in Lua don't need semicolons, but you can use them optionally:
print("Hello")
print("World"); print("!") -- Multiple statements on one line
Case Sensitivity
Lua is case-sensitive. print and Print are different identifiers.
Keywords
Lua has the following reserved keywords:
and break do else elseif end
false for function goto if in
local nil not or repeat return
then true until while
Variables & Types
Variable Declaration
Variables in Lua are global by default. Use local for local variables:
-- Global variables
name = "Alice"
age = 25
-- Local variables
local city = "New York"
local temperature = 72.5
Data Types
Lua has eight basic types:
-- nil
local nothing = nil
-- boolean
local isTrue = true
local isFalse = false
-- number
local integer = 42
local float = 3.14
-- string
local text = "Hello, Lua!"
local multiline = [[
This is a
multiline string
]]
-- function
local function greet()
return "Hello!"
end
-- userdata (C data)
-- thread (coroutines)
-- table
local array = {1, 2, 3, 4, 5}
local object = {name = "John", age = 30}
Type Checking
local value = 42
print(type(value)) -- "number"
value = "Hello"
print(type(value)) -- "string"
Functions
Function Declaration
-- Basic function
function sayHello(name)
print("Hello, " .. name .. "!")
end
-- Local function
local function add(a, b)
return a + b
end
-- Anonymous function
local multiply = function(a, b)
return a * b
end
Multiple Return Values
function getCoordinates()
return 10, 20
end
local x, y = getCoordinates()
print(x, y) -- 10 20
Variable Arguments
function sum(...)
local args = {...}
local total = 0
for i = 1, #args do
total = total + args[i]
end
return total
end
print(sum(1, 2, 3, 4, 5)) -- 15
Closures
function createCounter()
local count = 0
return function()
count = count + 1
return count
end
end
local counter = createCounter()
print(counter()) -- 1
print(counter()) -- 2
Tables
Tables are Lua's only data structuring mechanism. They can represent arrays, sets, records, graphs, trees, etc.
Array-like Tables
-- Array (1-indexed)
local fruits = {"apple", "banana", "orange"}
print(fruits[1]) -- "apple"
print(#fruits) -- 3 (length)
Dictionary-like Tables
-- Dictionary/Hash table
local person = {
name = "Alice",
age = 30,
city = "Boston"
}
print(person.name) -- "Alice"
print(person["age"]) -- 30
Mixed Tables
local mixed = {
"first", -- [1]
"second", -- [2]
name = "Mixed", -- ["name"]
count = 100 -- ["count"]
}
print(mixed[1]) -- "first"
print(mixed.name) -- "Mixed"
Table Operations
local t = {}
t.x = 10 -- Add field
t["y"] = 20 -- Add field
table.insert(t, "end") -- Add to end
table.remove(t, 1) -- Remove by index
-- Iterate over table
for key, value in pairs(t) do
print(key, value)
end
Control Flow
Conditional Statements
-- if-then-else
local age = 18
if age >= 18 then
print("Adult")
elseif age >= 13 then
print("Teenager")
else
print("Child")
end
Loops
-- while loop
local i = 1
while i <= 5 do
print(i)
i = i + 1
end
-- repeat-until loop
local j = 1
repeat
print(j)
j = j + 1
until j > 5
-- for loop (numeric)
for k = 1, 5 do
print(k)
end
-- for loop with step
for m = 1, 10, 2 do
print(m) -- 1, 3, 5, 7, 9
end
-- for loop (generic)
local fruits = {"apple", "banana", "orange"}
for index, fruit in ipairs(fruits) do
print(index, fruit)
end
Break and Return
for i = 1, 10 do
if i == 5 then
break -- Exit loop
end
print(i)
end
function findValue(table, target)
for i, value in ipairs(table) do
if value == target then
return i -- Exit function early
end
end
return nil
end
Strings
String Creation
local str1 = "Hello"
local str2 = 'World'
local str3 = [[Multi-line
string content]]
String Concatenation
local greeting = "Hello" .. " " .. "World"
print(greeting) -- "Hello World"
String Length
local text = "Lua programming"
print(#text) -- 15
print(string.len(text)) -- 15
String Functions
local text = "Hello, Lua!"
-- Convert case
print(string.upper(text)) -- "HELLO, LUA!"
print(string.lower(text)) -- "hello, lua!"
-- Substring
print(string.sub(text, 1, 5)) -- "Hello"
-- Find pattern
local pos = string.find(text, "Lua")
print(pos) -- 8
-- Replace
local newText = string.gsub(text, "Lua", "World")
print(newText) -- "Hello, World!"
String Formatting
local name = "Alice"
local age = 25
local formatted = string.format("Name: %s, Age: %d", name, age)
print(formatted) -- "Name: Alice, Age: 25"
Modules
Creating Modules
-- math_utils.lua
local M = {}
function M.add(a, b)
return a + b
end
function M.multiply(a, b)
return a * b
end
M.PI = 3.14159
return M
Using Modules
-- main.lua
local math_utils = require("math_utils")
print(math_utils.add(5, 3)) -- 8
print(math_utils.multiply(4, 7)) -- 28
print(math_utils.PI) -- 3.14159
Global vs Local Modules
-- Global approach (not recommended)
math_utils = {}
function math_utils.add(a, b)
return a + b
end
-- Local approach (recommended)
local math_utils = {}
local function add(a, b)
return a + b
end
math_utils.add = add
return math_utils
Luau Features
Luau is Roblox's version of Lua with additional features and optimizations.
Type Annotations
-- Function with type annotations
local function add(a: number, b: number): number
return a + b
end
-- Variable type annotations
local name: string = "Alice"
local age: number = 25
local isStudent: boolean = true
String Interpolation
local name = "World"
local greeting = `Hello, {name}!`
print(greeting) -- "Hello, World!"
local x, y = 10, 20
local coords = `Position: ({x}, {y})`
print(coords) -- "Position: (10, 20)"
Generics
-- Generic function
local function identity(value: T): T
return value
end
local numberResult = identity(42) -- number
local stringResult = identity("hello") -- string
Improved typeof
local value = 42
print(typeof(value)) -- "number" (more precise than type())
local instance = Instance.new("Part")
print(typeof(instance)) -- "Instance"
Continue Statement
for i = 1, 10 do
if i % 2 == 0 then
continue -- Skip even numbers
end
print(i) -- Only prints odd numbers
end
Compound Assignment
local x = 10
x += 5 -- equivalent to x = x + 5
x -= 3 -- equivalent to x = x - 3
x *= 2 -- equivalent to x = x * 2
x /= 4 -- equivalent to x = x / 4
Lua Quiz
Test your knowledge of Lua with this interactive quiz. Select the correct answer for each question.