🌙 Lua 5.0 - Basics
Basics
Updated at 2015-01-16 23:56
The original World of Warcraft used Lua 5.0. While newer Lua versions have introduced more features, vanilla uses a variant of Lua 5.0 which is all we've got.
This is the reason I've worked mainly with Lua 5.0.
Global by Default. A variable declared without the local
keyword is automatically a global variable.
local myVar = 10
Comments
-- This is a single-line comment
Data Types
nil
boolean
number -- floating-point doubles
string -- immutable text
table -- like dict or struct
local numberVal = 42
local stringVal = "Hello, World!"
local boolVal = true
Strings
local name = "Thrall"
local greeting = "Lok'tar, " .. name .. "!"
local len = string.len(greeting)
local sub = string.sub(greeting, 1, 6) -- "Lok'tar"
local str = string.format("Name: %s, Level: %d", "Thrall", 60)
Tables
Tables are the most important data structure in Lua. They work as arrays, lists, dictionaries, objects, classes (metatables), etc.
local myTable = {}
local colors = { "red", "green", "blue" } -- arrays are 1-indexed
local person = { name = "Alice", age = 30 } -- key-value
-- by index
print(colors[1])
-- by key
print(person.name)
print(person["age"])
table.insert(colors, "yellow")
table.remove(colors, 2) -- removes the element at index 2 ("green")
person.location = "Stormwind" -- add a new key
person.age = nil -- remove 'age'
Control Flow
if condition then
-- do something
elseif otherCondition then
-- do something else
else
-- fallback
end
while condition do
-- loop while condition is true
end
-- numeric for
for i = 1, 5 do
print(i)
end
-- generic for that iterates over tables
for key, value in pairs(person) do
print(key, value)
end
repeat
-- do something
until condition
Functions
Functions are first-class.
function greet(name)
print("Hello, " .. name .. "!")
end
-- equivalent definition
local greetAgain = function(name)
print("Hi again, " .. name)
end
Lua allows multiple return values:
function divide(dividend, divisor)
local quotient = dividend / divisor
local remainder = dividend % divisor
return quotient, remainder
end
local q, r = divide(13, 5)
print(q, r) -- prints 2.6 and 3
Error Handling
Lua 5.0 uses pcall()
(Protected Call) for catching errors during runtime:
local success, err = pcall(function()
-- code that may error
end)
if not success then
print("Error occurred: " .. err)
end
assert
throws an error if the condition is false:
local x = 10
assert(x == 10, "x must be 10!")