Lua Introduction

Lua is a lightweight, fast scripting language designed for embedding. It is one of the fastest scripting languages in the world — often faster than Python, Perl, and Ruby for comparable tasks.

Lua was created in 1993 at the Pontifical Catholic University of Rio de Janeiro, Brazil. Its name means "Moon" in Portuguese. Despite its small size (~300KB for the entire interpreter), Lua is used in production at some of the largest software companies in the world.

Where Lua is used

Area Examples
Game engines Roblox (Luau), LÖVE 2D, Defold, Gideros
Game scripting World of Warcraft addons, Civilisation VI
Embedded systems Cisco routers, Nmap security scanner
Databases Redis (EVAL command), MySQL Proxy
Web servers Nginx (OpenResty), HAProxy
Configuration Wireshark, Adobe Lightroom

Why Lua?

  • Tiny footprint — the entire interpreter compiles to ~300KB
  • Very fast — consistently one of the fastest scripting languages
  • Easy to embed — designed from the start to be called from C/C++
  • Portable — runs on anything from microcontrollers to supercomputers
  • Simple syntax — can be learned in a day

Hello World

LUA
print("Hello, Nepal!")
Bash
lua hello.lua    # run with Lua interpreter

Variables and Types

LUA
-- Lua has 8 types: nil, boolean, number, string, function, table, userdata, thread
local name = "Sita"        -- string
local age = 21             -- number (all numbers are floats in Lua 5.3+)
local active = true        -- boolean
local nothing = nil        -- nil (like null/undefined)

-- Strings
local greeting = "Hello, " .. name .. "!"   -- concatenation with ..
print(#greeting)          -- 13 (string length with #)
print(string.upper(name)) -- "SITA"
print(string.format("Age: %d", age))

Comments

LUA
-- Single line comment

--[[
Multi-line
comment
]]

What you will learn

Chapter Topic
Tables Arrays, dictionaries, and data structures
Control Flow if/else, loops
Functions Closures, higher-order functions
Metatables OOP, operator overloading
Coroutines Cooperative multitasking
Error Handling pcall, xpcall, assertions