🚀 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.

-- Lua 5.4: Hello World print("🌙 Hello from Lua! CodeOrbitPro") -- Basic info print(_VERSION) --> Lua 5.4

📐 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
-- Single line comment --[[ multi-line comment ]] -- Global variable age = 25 -- Local variable local name = "CodeOrbitPro" print(name, age) -- Multiple assignment x, y = 10, 20 x, y = y, x -- swap print(x, y) --> 20 10

📊 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)
print(type(nil)) --> nil print(type(true)) --> boolean print(type(42)) --> number print(type("Lua")) --> string print(type(print)) --> function print(type({})) --> table -- Falsy values: false and nil only if not false then print("false is falsy") end if not nil then print("nil is falsy") end if 0 then print("0 is truthy") end --> prints

🧮 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)
print(10 + 5) --> 15 print(10 / 3) --> 3.3333 print(10 // 3) --> 3 (floor division) print(10 % 3) --> 1 print(2 ^ 3) --> 8 print("Hello" .. " " .. "Lua") --> Hello Lua -- Logical print(true and false) --> false print(not true) --> false print(10 > 5 and "yes" or "no") --> yes (ternary idiom) -- Relational print(10 ~= 5) --> true print(10 == "10") --> false (no coercion)

🔀 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
score = 85 if score >= 90 then grade = "A ⭐" elseif score >= 80 then grade = "B ⭐" else grade = "C" end print("Grade:", grade) -- Ternary idiom age = 17 status = (age >= 18) and "adult" or "minor" print(status)

🔄 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)
-- numeric for for i = 1, 5 do io.write(i, " ") --> 1 2 3 4 5 end print() -- while local a = 3 while a > 0 do print("while", a) a = a - 1 end -- repeat until local b = 3 repeat print("repeat", b) b = b - 1 until b == 0 -- generic for local days = {"Sun", "Mon", "Tue"} for idx, value in ipairs(days) do print(idx, value) end

⚙️ 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)
function add(a, b) return a + b end local mul = function(a, b) return a * b end print(add(5, 3)) --> 8 print(mul(4, 3)) --> 12 -- Multiple returns function stats(...) local t = {...} local max = math.max(table.unpack(t)) local min = math.min(table.unpack(t)) return min, max end mn, mx = stats(10, 4, 7, 22) print(mn, mx) --> 4 22 -- Closure function makeCounter() local count = 0 return function() count = count + 1 return count end end c = makeCounter() print(c(), c()) --> 1 2

🗂️ 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
-- Array part local fruits = {"apple", "banana", "cherry"} print(fruits[1]) --> apple (1-indexed) -- Dict part fruits["color"] = "red" fruits.price = 2.5 for k, v in pairs(fruits) do print(k, v) end -- Table functions table.insert(fruits, "date") table.remove(fruits, 2) -- removes banana print(table.concat(fruits, ", ")) --> apple, cherry, date -- Length (#) on array part print(#fruits) --> 3

🔮 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)
-- Simple class Animal = {name = "Animal"} function Animal:new(name) local obj = {name = name} setmetatable(obj, self) self.__index = self return obj end function Animal:speak() print(self.name .. " makes a sound") end -- Inheritance Dog = Animal:new() function Dog:speak() print(self.name .. " barks") end local a = Animal:new("Generic") a:speak() --> Generic makes a sound local d = Dog:new("Rex") d:speak() --> Rex barks -- Metamethod example local mt = { __add = function(t1, t2) local res = {} for k, v in pairs(t1) do res[k] = v end for k, v in pairs(t2) do res[k] = v end return res end } t1 = {a=1}; t2 = {b=2}; setmetatable(t1, mt); setmetatable(t2, mt) t3 = t1 + t2 for k,v in pairs(t3) do print(k,v) end --> a 1, b 2

📝 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
s = "Lua Programming" print(#s) --> 15 print(string.sub(s, 1, 3)) --> Lua print(string.upper(s)) --> LUA PROGRAMMING print(string.rep("ha", 3)) --> hahaha -- Pattern matching date = "2026-03-10" yy, mm, dd = string.match(date, "(%d+)-(%d+)-(%d+)") print(yy, mm, dd) --> 2026 03 10 -- Format name = "CodeOrbitPro" print(string.format("Hello %s, value = %.2f", name, 3.14159))

💾 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
-- Write file local f = io.open("codeorbit_lua.txt", "w") f:write("CodeOrbitPro Lua Track\n") f:write("Line 2\n") f:close() -- Read file f = io.open("codeorbit_lua.txt", "r") local content = f:read("*all") print(content) f:close() -- Using io.lines (auto close) for line in io.lines("codeorbit_lua.txt") do print("Line:", line) end -- Append f = io.open("codeorbit_lua.txt", "a") f:write("Appended line\n") f:close()

📦 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
-- Creating a simple module: mymath.lua -- (simulated here as table) local mymath = {} function mymath.add(a,b) return a+b end function mymath.sub(a,b) return a-b end -- return mymath -- Using require (would be in another file) -- local mm = require "mymath" -- print(mm.add(10,5)) -- Built-in modules print(math.sqrt(144)) --> 12.0 print(os.date()) --> current date/time print(table.concat({"a","b"},"-")) --> a-b

🛡️ 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
local ok, result = pcall(function() error("simulated error") end) if not ok then print("Caught error:", result) --> Caught error: simulated error end -- Using assert local function safe_divide(a,b) assert(b ~= 0, "division by zero") return a/b end -- pcall with assert local ok, res = pcall(safe_divide, 10, 0) if not ok then print("error:", res) end --> error: division by zero -- xpcall with traceback local function traceback(err) print("error trace:", debug.traceback(err)) end xpcall(function() error("fail") end, traceback)

⚡ 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
-- Coroutine example co = coroutine.create(function() for i = 1, 3 do print("coroutine", i) coroutine.yield(i) end end) print(coroutine.resume(co)) --> coroutine 1, true 1 print(coroutine.resume(co)) --> coroutine 2, true 2 print(coroutine.resume(co)) --> coroutine 3, true 3 print(coroutine.resume(co)) --> false (dead) -- Garbage collection print(collectgarbage("count")) -- memory in KB collectgarbage("collect") -- force full GC -- Using coroutine as iterator function permgen(a, n) if n == 0 then coroutine.yield(a) else for i = 1, n do a[n], a[i] = a[i], a[n] permgen(a, n-1) a[n], a[i] = a[i], a[n] end end end -- wrap as iterator function permutations(a) local co = coroutine.create(function() permgen(a, #a) end) return function() local code, res = coroutine.resume(co) return res end end for p in permutations({"a","b","c"}) do print(table.concat(p, ",")) end