Skip to content
LumenaryAcademy
Foundations 45 min

Getting started with Lua

Where Lua came from, why so many programs carry it inside them, and your first scripts.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

A language made to live inside other programs

Most languages expect to be the main program. You write a Python or Java application, and it runs. Lua was designed for a different job: to be a small language that lives inside a larger program, written in C, C++ or something else, so that the larger program's users can customise and extend it without recompiling it.

Think of a game engine. The engine itself, with its graphics, physics and sound, is written in C++ for speed. But the behaviour of each character, each level and each menu changes constantly while a game is being designed, often by people who are not engine programmers. If every change meant recompiling the engine, the team would crawl. So the engine embeds a scripting language: the characters' behaviour lives in scripts, loaded and run by the engine, changed in seconds.

Lua is the language most often chosen for that job, because it is small (the whole interpreter is a few hundred kilobytes of machine code), fast for an interpreted language, written in portable ISO C, and has a clean interface for C programs. You meet it in many places:

  • Games. World of Warcraft's user-interface add-ons are written in Lua. Roblox uses Luau, a language derived from Lua 5.1 with gradual typing, for every game on its platform. Engines and frameworks such as LÖVE and Defold use Lua as their main language.
  • Editors and tools. The Neovim editor is configured and extended in Lua. The network analyser Wireshark accepts protocol dissectors written in Lua, and the document converter Pandoc accepts Lua filters. The TeX engine LuaTeX embeds it.
  • Servers and databases. Redis runs Lua scripts atomically inside the database. OpenResty builds web applications inside the nginx web server with Lua, and HAProxy can be extended with it.
  • Applications and devices. Adobe Lightroom used Lua for much of its application logic, and Lua runs on small embedded systems and microcontrollers, where its tiny footprint matters.

Lua is also a good language on its own. It has one data structure, the table, that serves as array, dictionary, record, object and module; functions are values; closures, coroutines and metatables let you build almost any abstraction from a few parts. You can learn the whole language in days and keep finding depth in it for years.

History & global context

From Tecgraf to Lua 5.5

Lua was created in 1993 at Tecgraf, the computer graphics group of the Pontifical Catholic University of Rio de Janeiro (PUC-Rio) in Brazil, by Roberto Ierusalimschy, Luiz Henrique de Figueiredo and Waldemar Celes. Tecgraf built engineering software for industrial partners, notably the oil company Petrobras, and needed a way to let those programs be configured and scripted. At the time, Brazil had strict trade barriers on imported hardware and software, which encouraged teams to build their own tools rather than buy them. Two small in-house languages came first, DEL for data entry and SOL ("Simple Object Language"; sol also means "sun" in Portuguese). Lua replaced and generalised both, and its name is the Portuguese word for "moon". It is written Lua, a name, not an acronym: not "LUA".

The main versions mark the language's growth:

VersionYearWhat it brought
1.11994the first public release
5.02003metatables, coroutines, full lexical closures, a register-based virtual machine, and the MIT licence
5.12006a new module system built on require and the package library, an incremental garbage collector; the version LuaJIT and Luau grew from
5.22011_ENV for controlling global variables, goto
5.32015a real integer type alongside floats, bitwise operators, the utf8 library
5.42020<const> and <close> local variables, a generational garbage collector
5.5—global declarations, named vararg tables, read-only loop variables; the current version in 2026

Lua is still developed by the same small team at PUC-Rio. They are famously careful: features are added only when they are clearly worth their cost in size and complexity, and they are willing to change the language between versions (each 5.x is a little incompatible with the previous one) rather than keep a mistake forever. The language's definition is its reference manual, written by the three authors; there is no separate standard. This course uses Lua 5.5 and points out where it differs from Lua 5.4, which you will still meet often.

Mechanisms, not policies

Lua's guiding design rule is to provide mechanisms rather than policies. Lua has no classes, but it has metatables, from which you can build classes in several styles. It has no module keyword, but tables and functions make modules. It has no threads, but coroutines let you build schedulers. The language stays small, and each application that embeds it can build the policies it needs. You will see this idea in almost every lesson.

DefinitionsH

Installing Lua and running code

Getting Lua. The official distribution, from lua.org/download.html, is source code that builds with a plain make on Linux and macOS in a few seconds, because it is pure ISO C with no dependencies. Package managers have it too (brew install lua with Homebrew, or your Linux distribution's packages, which are often a version behind), and LuaBinaries provides builds for Windows. To try something without installing anything, the official Lua demo runs code in your browser.

Check your version:

bash
lua -v            # prints the version, e.g. "Lua 5.5.1  Copyright (C) 1994-2026 Lua.org, PUC-Rio"

The interactive interpreter. Run lua with no arguments and you get a prompt where you can type statements or expressions; an expression's value is printed for you. A short session looked like this:

text
Lua 5.5.1  Copyright (C) 1994-2026 Lua.org, PUC-Rio
> 2 ^ 10
1024.0
> "moon" .. "light"
moonlight
> x = 7 * 6
> x
42

Leave with Ctrl-D (Ctrl-Z then Enter on Windows) or os.exit().

Running a script. Save code in a file ending in .lua and run lua hello.lua. Other useful options: lua -e 'print(1 + 1)' runs code given on the command line, lua -i hello.lua runs a script and then leaves you at the prompt with its variables available, and arguments after the script name arrive in a global table called arg.

Definition— Chunk

A piece of Lua code that is compiled and run as a unit: a file, a string given to lua -e, or a line typed at the prompt. Lua first compiles a chunk into bytecode for its virtual machine, then runs it. The luac program does the compilation step on its own (luac -l hello.lua lists the bytecode), but you rarely need it: lua compiles in memory and is fast.

Worked examplesH

A first script

lua
-- A first Lua program. Run it with: lua hello.lua
local name = "Rafaela"
local born = 1993
local age = 2026 - born

print("Hello, " .. name .. "!")
print("Lua appeared in " .. born .. ", so in 2026 it is " .. age .. " years old.")
print("print separates", "its arguments", "with tabs")
io.write("io.write adds no newline", "\n")
print(string.format("%s has %d letters; %.1f%% of them are vowels.", name, #name, 4 / 7 * 100))
print(("lua"):upper(), #"moon", type(name), type(age), type(print))
print(_VERSION)

It printed:

text
Hello, Rafaela!
Lua appeared in 1993, so in 2026 it is 33 years old.
print separates	its arguments	with tabs
io.write adds no newline
Rafaela has 7 letters; 57.1% of them are vowels.
LUA	4	string	number	function
Lua 5.5

Line by line:

  • Comments start with -- and run to the end of the line. A long comment is written --[[ ... ]] and can span lines.
  • local name = "Rafaela" declares a local variable. Variables have no declared type; values do. Always write local for your own variables: a name assigned without local becomes a global, which is a common source of bugs, as the next lesson explains.
  • .. concatenates strings. Numbers are converted to strings automatically when concatenated, which is why "in " .. born works.
  • print takes any number of arguments, converts each to a string, and separates them with tab characters; it ends with a newline. io.write writes exactly what you give it, with no separators or newline.
  • string.format works like C's printf: %s a string, %d an integer, %.1f a number with one decimal, %% a percent sign.
  • #name is the length operator: for a string, its number of bytes.
  • ("lua"):upper() calls a string method. Strings share the string library as their methods, so s:upper() means string.upper(s). The parentheses around the literal are needed only because it is a literal.
  • type returns the name of a value's type as a string.
  • _VERSION is a global string naming the running version, here Lua 5.5.

Lua needs no semicolons (you may write them) and no special layout: line breaks and indentation are for the reader. Blocks end with the keyword end.

Worked examplesH

A taste of real Lua

Here is a slightly bigger program that uses ideas from the next few lessons: a table of records, a function, a sort with a comparison function, and a loop.

lua
-- A taste of Lua: a table of records, a function, a loop and a sort.
local languages = {
  { name = "Lua",    year = 1993, home = "Brazil" },
  { name = "Perl",   year = 1987, home = "United States" },
  { name = "Python", year = 1991, home = "Netherlands" },
  { name = "Ruby",   year = 1995, home = "Japan" },
  { name = "Elixir", year = 2012, home = "Brazil" },
}

local function describe(lang)
  local gap = lang.year - 1993
  if gap == 0 then
    return lang.name .. " (" .. lang.home .. ") is our language"
  elseif gap < 0 then
    return lang.name .. " (" .. lang.home .. ") is " .. -gap .. " years older than Lua"
  else
    return lang.name .. " (" .. lang.home .. ") is " .. gap .. " years younger than Lua"
  end
end

table.sort(languages, function(a, b) return a.year < b.year end)

local from_brazil = 0
for i, lang in ipairs(languages) do
  print(i, describe(lang))
  if lang.home == "Brazil" then from_brazil = from_brazil + 1 end
end
print("languages from Brazil in this list: " .. from_brazil)

It printed:

text
1	Perl (United States) is 6 years older than Lua
2	Python (Netherlands) is 2 years older than Lua
3	Lua (Brazil) is our language
4	Ruby (Japan) is 2 years younger than Lua
5	Elixir (Brazil) is 19 years younger than Lua
languages from Brazil in this list: 2

You can already read most of it:

  • { name = "Lua", year = 1993, home = "Brazil" } is a table used as a record, and languages is a table of tables used as a list. Tables are Lua's only data structure, and lesson 3 is about them.
  • local function describe(lang) ... end defines a function. Functions are values, which is why the next line can pass an anonymous function(a, b) ... end to table.sort to say how to compare two records.
  • for i, lang in ipairs(languages) do ... end visits the list in order, giving each position and value. Lists in Lua count from 1, not 0.
  • -gap is unary minus, and if ... elseif ... else ... end is the conditional.
IntuitionH

What embedding looks like

The heart of Lua's design is that a host program can load code, decide exactly what that code is allowed to see, and run it. You can see the idea without writing any C, because Lua's own load function does it:

lua
-- Programs that embed Lua run scripts written by their users.
-- load() compiles a string of Lua code; its fourth argument is the
-- table the script sees as its global variables (its environment).
local user_script = [[
  greeting = "Habari"
  area = width * height
  shout = string and string.upper
]]

local env = { width = 4, height = 3 }   -- all the script is allowed to see
local chunk = assert(load(user_script, "settings", "t", env))
chunk()

print(env.greeting, env.area, env.shout)
print(greeting)                          -- the script's globals stayed in env

It printed:

text
Habari	12	nil
nil

load compiled the user's script into a function, a chunk, without running it. The fourth argument gave the script its own table of global variables, its environment, containing only width and height. When the chunk ran, its "global" assignments went into that table, and it could not see print, string or anything else from the outside, so shout came out nil. The host's own globals were untouched.

An application that embeds Lua does exactly this from C: it creates a Lua state, puts into the environment the functions it wants scripts to call ("spawn an enemy", "set the font size"), loads the user's script, and runs it. Lesson 8 shows the C side.

Analogy, not a formal construction

Embedding Lua is like giving a visiting craftsperson a workshop. You choose which tools are on the bench (the environment), they build whatever they like with those tools, and the rest of your house stays locked. A different visitor can get a different bench.

ExplanationH

How people work with Lua

Because Lua is usually embedded, "which Lua" depends on where you meet it, and that is the first thing a professional checks:

  • Standalone Lua 5.4 or 5.5, as in this course, for scripts and tools.
  • LuaJIT, a very fast independent implementation compatible with Lua 5.1, used by OpenResty and many games. Lesson 8 describes it.
  • Luau in Roblox, which adds types and its own tooling.
  • Embedded Lua in Neovim (LuaJIT), Redis (Lua 5.1), Wireshark and others, each with its own built-in libraries and sometimes restrictions.

Code that sticks to the common core runs on all of them; the differences are in a few features (integers, goto, <close>, global) and in the libraries the host provides. When you read documentation for a host, look for the Lua version first.

Most Lua programmers keep the reference manual open: it is short, complete and well written, and reading it end to end is a realistic goal. The book Programming in Lua, by Roberto Ierusalimschy, is the classic deeper guide; its official site has details of the current edition.

Note

Lua is one of the very few widely used programming languages created in Latin America. Its authors have told its story in a paper, "The Evolution of Lua", for the HOPL (History of Programming Languages) conference in 2007; it is listed with their other papers on lua.org, and it is a fine read about how a small, careful team can build something used everywhere.

Exercises

Exercises

1. Getting started with Lua

Warm-upHuman

What does the name Lua mean, and how should it be written?

Choose one

2. Getting started with Lua

CoreComputational

What does this program print?

local major, minor = 5, 5
print("Lua " .. major .. "." .. minor .. " is " .. 2026 - 1993 .. " years after Lua 1.0")

3. Getting started with Lua

Warm-upComputational

What number does this program print?

print(#"Rio de Janeiro")

4. Getting started with Lua

CoreComputational

What does this program print? Type the line exactly, including spaces.

print(string.format("%-5s|%3d|%.2f", "ab", 7, 2 / 3))

5. Getting started with Lua

CoreComputational

What does this program print?

print(type(type(42)))

6. Getting started with Lua

StretchComputational

What does this program print?

local env = { x = 10 }
local chunk = load("y = x * 2", "calc", "t", env)
chunk()
io.write(tostring(env.y), " ", tostring(y), "\n")

7. Getting started with Lua

CoreHuman

Which of these is the best example of Lua's principle of mechanisms, not policies?

Choose one

8. Getting started with Lua

CoreHuman

Which statements about the Lua family are accurate? Choose all that apply.

Choose all that apply

Further reading and resources

  • Lua download pageThe official source releases, with links to binaries and the online demo.
  • Lua 5.5 Reference ManualThe definition of the language. Section 7 describes the lua command and its options.
  • About LuaThe official overview of what Lua is and why it was made.
  • Lua demoRun small Lua programs in your browser.
  • Programming in Lua · Roberto IerusalimschyThe official book by Lua's chief architect.