Lua logo

Lua Beginner

Lightweight embeddable scripting language — fast execution, simple syntax, and powerful data description via tables.

1 Variables & Scope

By default, variables in Lua are global unless explicitly declared with the local keyword. Always prefer local scope for performance and to prevent polluting environment namespaces.

lua · variables.lua
-- This is a single-line comment
--[[
    This is a multi-line
    comment block
--]]

local username = "vidux"  -- Block-scoped local variable
globalVar = "accessible everywhere" -- Global variable

print(username)
Lua doesn't require semicolons (;) at the end of statements, though they are syntactically valid.

2 Data Types

Lua is dynamically typed. Variables don't have types; only the values assigned to them do. There are 8 basic types, with the core 6 used inside daily logic structures.

nil Non-value / unassigned local empty = nil
boolean true or false choices local active = true
number Double floats / Integers local ratio = 3.14
string Immutable text string local raw = "hello"
function First-class executable local f = function() end
table Only data structure local data = {}

3 Conditionals

Control program flows using if-then-elseif-else blocks. Note that only false and nil evaluate to false; numbers like 0 and empty strings "" evaluate to true.

lua · logic.lua
local score = 85

if score >= 90 then
    print("Excellent execution")
elseif score >= 70 then
    print("Passable configuration")
else
    print("Failure condition triggered")
end

-- Logical operators: and, or, not. Inequality is ~=
if score ~= 0 and not structuralError then
    -- process data
end

4 Loops & Iteration

Lua handles repetition using numerical for bounds, generic for iterators over tables, alongside while and repeat-until loops.

lua · loops.lua
-- Numerical For: (start, stop, step)
for i = 1, 3 do
    print("Index counter: " .. i) -- '..' is the string concatenation operator
end

-- While conditional loop
local count = 3
while count > 0 do
    count = count - 1
end

5 Functions

Functions are first-class citizens. They can be assigned to variables, passed as arguments, and returned from other routines. They also support multiple return values natively.

lua · functions.lua
-- Multi-return function signature
local function computeMetrics(width, height)
    local area = width * height
    local perimeter = (width + height) * 2
    return area, perimeter
end

-- Receiving tuple variables
local myArea, myPerim = computeMetrics(10, 20)

6 Tables (Arrays & Dictionaries)

Tables are the sole data structuring mechanism in Lua. They function as indexed arrays or key-value hash dictionaries interchangeably.

lua · tables.lua
-- Dictionary structure assignment
local config = {
    title = "Engine Launcher",
    fps = 60
}
print(config.title) -- Dot syntax sugar for config["title"]

-- Array structure assignment (1-indexed base!)
local tools = {"compiler", "linker", "debugger"}
print(tools[1])     -- Outputs "compiler" (1 is the first entry!)
print(#tools)        -- '#' operator fetches array array length count
Unlike almost all mainstream modern environments, **Lua arrays are 1-indexed**. In standard sequences, `array[0]` evaluates to `nil`. Keep this in mind when implementing algorithms!

7 Metatables & OOP

Metatables allow tables to override operational behaviors when interacting with keys, arithmetic signs, or function inheritance chains via fallback definitions called metamethods.

lua · metatables.lua
local Vector = {}
Vector.__index = Vector -- Fallback lookup mapping routing handler

function Vector.new(x, y)
    local instance = setmetatable({}, Vector)
    instance.x = x
    instance.y = y
    return instance
end

function Vector:printCoords()
    print(self.x, self.y) -- ':' syntax auto-injects 'self' implicit reference
end

local position = Vector.new(105, 240)
position:printCoords()

8 Modules & Standard Libs

Break up codebases across distinct files by packaging components into local tables returned at the end of scripts, and loaded via require calls.

lua · modules.lua
-- Inside math_utils.lua file scope:
local utils = {}
function utils.add(a, b) return a + b end
return utils

-- Inside main.lua entry runtime execution file:
local mathUtils = require("math_utils")
local sumResult = mathUtils.add(40, 2)

-- Standard native modules include: math, table, string, os, io
local randomValue = math.random(1, 100)
Lua is incredibly lightweight and efficient, making it the premier choice for extension modding layers, configuration schemas, and embedded architectures.