🚀 Lua Introduction
🎯 Complete Definition
Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description. Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode with a register-based virtual machine, and has automatic memory management with incremental garbage collection.
🔬 Core Characteristics
- Lightweight: Small C library (~300kB), fast interpreter
- Embeddable: Easy to integrate with C/C++, used in games (World of Warcraft, Roblox), embedded systems, Redis, Nginx
- Multi-paradigm: Procedural, functional, object-oriented (via metatables), data-driven
- Dynamic typing: Variables have no types; values do
- Associative arrays: The single universal data structure "table"
- Extensible semantics: Metatables and metamethods for operator overloading, inheritance
- Automatic memory: Incremental garbage collector
📊 Industry Usage
Lua is a leading scripting language in game development (Roblox, World of Warcraft, Angry Birds), embedded devices (Adobe Lightroom, Wireshark), and configuration (Awesome WM, Nginx). It ranks among the top 20 most popular languages (TIOBE) and is praised for its performance and simplicity.
📐 Syntax & Basics
🎯 Complete Definition
Lua syntax is clean and simple. Statements end with semicolons (optional). Comments use -- for single line and --[[ ... ]] for multiline. Variables are global by default; local variables must be explicitly declared. Blocks are delimited by keywords like then, end, do, end. Lua is case-sensitive.
🏷️ Basic Rules
- Identifiers: letters, digits, underscores, not starting with digit
- Reserved words: and, break, do, else, elseif, end, false, for, function, if, in, local, nil, not, or, repeat, return, then, true, until, while
- Variable scope: use 'local' for local; otherwise global
- Multiple assignment: a, b = 10, 20
- Chunks: any sequence of statements; can be stored in files or run interactively
📊 Data Types
🎯 Complete Definition
Lua is dynamically typed. There are eight basic types: nil, boolean, number, string, function, userdata, thread, table. Values have types, variables do not. The type() function returns the type as a string.
🏷️ Type Details
- nil: absence of value; any undeclared variable is nil
- boolean: true or false; only nil and false are falsy; everything else truthy
- number: double-precision floating point (int64 optionally compiled)
- string: immutable sequence of 8-bit bytes (can hold any data)
- function: first-class values, can be stored in variables
- userdata: C data passed to Lua; for embedding
- thread: independent execution lines (coroutines)
- table: associative arrays (the core data structure)
🧮 Operators
🎯 Complete Definition
Lua operators include arithmetic, relational, logical, and concatenation. Operator precedence follows conventional rules. Most operators can be overloaded using metatables.
📋 Operator Categories
- Arithmetic: +, -, *, /, ^ (exponentiation), // (floor division), % (modulo)
- Relational: ==, ~=, <, >, <=, >= (results in boolean)
- Logical: and, or, not (short-circuit)
- Concatenation: .. (string concatenation)
- Length: # (length operator for strings and tables)
🔀 Control Flow
🎯 Complete Definition
Control structures in Lua: if, then, else, elseif, end. There is no switch statement. Conditions can be any expression; only false and nil are considered false.
🏗️ Structures
- if condition then ... end
- if condition then ... else ... end
- if cond1 then ... elseif cond2 then ... else ... end
- No ternary operator but idiom:
cond and value1 or value2
🔄 Loops
🎯 Complete Definition
Lua supports while, repeat (until), for (numeric and generic). The break statement exits a loop. No continue in pure Lua.
🏗️ Loop Variants
- while condition do ... end
- repeat ... until condition (loop at least once)
- for var = start, end, step do ... end (numeric)
- for k, v in pairs(t) do ... end (generic)
- for i, v in ipairs(t) do ... end (array-like)
⚙️ Functions
🎯 Complete Definition
Functions are first-class values, anonymous, can have variable arguments (...) and multiple returns. Lexical scoping and closures are supported.
🏗️ Function Features
- function f(params) ... end (syntactic sugar)
- f = function(params) ... end (function value)
- return a, b (multiple returns)
- ... vararg expression inside function
- function t:method(...) end (method with self)
🗂️ Tables
🎯 Complete Definition
Tables are the sole data structuring mechanism in Lua. They are associative arrays (key-value pairs). Keys can be any value except nil. Tables are dynamically created and can be used as arrays, dictionaries, objects, modules.
🏗️ Table Operations
- t = {} empty table
- t = {1,2,3; name="Lua"} mixed
- t.key or t["key"] access
- #t length for array part (holes count inconsistently)
- table.insert, table.remove, table.sort, table.concat
🔮 Metatables & OOP
🎯 Complete Definition
Metatables allow changing the behavior of tables. They define metamethods like __index, __add, __call. This mechanism enables operator overloading, inheritance, and OOP.
🏗️ OOP with Tables
- setmetatable(t, mt) assigns metatable
- __index for inheritance (fallback)
- __newindex for updates
- __add, __sub, __call for operator overloading
- Class syntax using
:(self sugar)
📝 Strings
🎯 Complete Definition
Strings are immutable sequences of bytes. Lua handles 8-bit clean strings, so they can contain any binary data. String library provides powerful manipulation functions.
🏗️ String Functions
- string.len(s), #s length
- string.sub(s, i, j) substring
- string.format(format, ...) C-like formatting
- string.find, string.gsub, string.match, string.gmatch pattern matching (not regex, but powerful patterns)
- string.byte, string.char convert bytes
💾 I/O & File Handling
🎯 Complete Definition
Lua I/O library provides two models: simple (io.) and complete (file handles). Supports reading/writing files, standard I/O.
🏗️ File Operations
- io.open(filename, mode) returns file handle
- file:read("*all", "*line", "*number")
- file:write(...)
- io.input(), io.output() set default files
- io.lines() iterator over lines
📦 Modules & Packages
🎯 Complete Definition
Lua modules are tables containing functions and data. require loads a module, caching it. Package loaders search in package.path for Lua files and package.cpath for C libraries.
🏗️ Module Definition
- module pattern: return a table
- package.path search path for Lua modules
- require "modname" loads module
- Common libraries: math, table, string, io, os, debug
🛡️ Error Handling
🎯 Complete Definition
Lua uses error() to raise errors and pcall() (protected call) or xpcall() to handle them. Errors can be any Lua value (string, table).
🏗️ Handling
- error(msg [, level]) raises an error
- pcall(func, ...) returns status + results/error
- xpcall(func, err_handler) with error handler
- assert(condition, msg) raises if condition falsy
⚡ Advanced (Coroutines, GC)
🎯 Complete Definition
Lua supports coroutines (collaborative multithreading). They have their own stack and can suspend/resume. Garbage collection is incremental; can be controlled via collectgarbage.
🏗️ Coroutine Functions
- coroutine.create(f) creates coroutine
- coroutine.resume(co, ...) starts/resumes
- coroutine.yield(...) suspends
- coroutine.status(co) status
- Great for iterators, state machines