Hello World (first programs) · Beginner · 14 min
Hello World in Lua: tables, 1-based arrays and embedding
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Lua 5.5.0 (lua5.5 package) · upstream Lua 5.5.1
You will install Lua 5.5, run print in the interpreter and from a script, read a name from the keyboard, and use a single table as both a list and a map without falling into the 1-based indexing trap.
On this page
Lua is a small scripting language from PUC-Rio in Brazil. Most people meet it inside something else: the scripting layer of a game engine, a Neovim config file, an Nginx server running OpenResty, or the firmware of a router. That is what it was designed for. The whole implementation is a few tens of thousands of lines of portable C, so a program written in C can carry Lua inside it and let users script it.
Two things make Lua feel different from Python or JavaScript. It has exactly one data structure, the table, which does the job of arrays, dictionaries, objects and modules. And its lists start at 1, not 0. This tutorial shows both, and the mistakes they cause.
You use Lua 5.5, the current major version. Ubuntu 26.04 packages 5.5.0; the newest upstream release is 5.5.1, from August 2026, and nothing here differs between them. You work in a throwaway folder, ~/hello-lua-demo, and delete it at the end.
Step 1 · Install Lua 5.5
On Ubuntu 26.04, install the lua5.5 package:
sudo apt update
sudo apt install -y lua5.5
lua5.5 -vThe command is called lua5.5, not lua, so that several Lua versions can be installed side by side. Some systems also offer a plain lua command that points at one of them; this tutorial always types lua5.5 so you know which version runs.
On Windows, the simplest route is WSL: install Ubuntu from the Microsoft Store and follow the Ubuntu commands. On macOS, Homebrew's brew install lua installs a recent Lua under the name lua; check its version with lua -v and use lua wherever this page says lua5.5. The official source code and links to prebuilt binaries are at lua.org/download.html.
Check it worked
lua5.5 -v prints one line starting Lua 5.5.0 (or a later 5.5 release) followed by a copyright notice from Lua.org, PUC-Rio. If you see command not found, read the last lines of the apt install output for an error and run it again.
Step 2 · Say hello in the interactive interpreter
Start the interpreter with no arguments:
lua5.5You get a > prompt. Type these two lines, pressing Enter after each:
print("Hello, world!")
2 + 3The first line calls the built-in print function, which writes its arguments followed by a newline. The second line is an expression on its own; the interpreter evaluates it and shows the result, 5. In a script file a bare expression like that is an error, so this only works at the prompt.
Leave the interpreter with Ctrl+D, or by typing os.exit().
For a quick one-line test you can skip the prompt and pass code with -e:
lua5.5 -e 'print("Hello from -e")'Check it worked
At the prompt, print("Hello, world!") shows Hello, world! and 2 + 3 shows 5. The -e command prints Hello from -e and returns you straight to the shell.
Step 3 · Write and run hello.lua
Make the demo folder and create a script:
mkdir -p ~/hello-lua-demo
cd ~/hello-lua-demo
cat > hello.lua <<'LUA'
#!/usr/bin/env lua5.5
-- hello.lua: the first Lua script
print("Hello, world!")
LUA
lua5.5 hello.luaYou can type the three lines into an editor and save them as hello.lua instead. Line by line:
#!/usr/bin/env lua5.5is the shebang. It tells Linux and macOS which program runs the file when you execute it directly. Lua itself skips a first line that starts with#, so the line is harmless when you runlua5.5 hello.lua.-- hello.lua: ...is a comment. Two hyphens start a comment that runs to the end of the line.print("Hello, world!")prints the text. No semicolon is needed, there is nomainfunction, and nothing has to be imported: the file is run from top to bottom.
Make the file executable and run it without naming the interpreter:
cd ~/hello-lua-demo
chmod +x hello.lua
./hello.luaCheck it worked
Both lua5.5 hello.lua and ./hello.lua print Hello, world!. If ./hello.lua says Permission denied, the chmod +x line did not run.
Step 4 · See the bytecode Lua compiles to
Lua is not read line by line as you might expect. Before a script runs, Lua compiles the whole file into bytecode for its own virtual machine, then runs that. A syntax error anywhere in the file stops it before the first line executes. The package includes luac5.5, the compiler on its own, which lets you see this:
cd ~/hello-lua-demo
luac5.5 -p hello.lua && echo "syntax OK"
luac5.5 -l -p hello.lua-pparses the file and reports errors without writing any output file. It is a quick syntax check.-llists the instructions the compiler produced.
Check it worked
The first command prints syntax OK. The listing starts with a line something like main <hello.lua:0,0> (5 instructions at ...), followed by a handful of numbered instructions. Among them you can pick out GETTABUP (fetch the global print), LOADK (load the string), CALL (call the function) and RETURN. That is your whole program as the Lua virtual machine sees it.
Step 5 · Read a name from the keyboard
Create greet.lua, which asks for a name and greets you:
cd ~/hello-lua-demo
cat > greet.lua <<'LUA'
io.write("What is your name? ")
local name = io.read("l")
if name == nil or name == "" then
name = "stranger"
end
print("Hello, " .. name .. "!")
print("Your name is " .. #name .. " bytes and " .. utf8.len(name) .. " characters long.")
LUAWhat each part does:
io.write(...)prints without adding a newline, so your answer appears on the same line as the question.io.read("l")reads one line from the keyboard and drops the newline you typed. At the end of input (an empty pipe, or Ctrl+D) it returnsnil.local namecreates a variable that exists only in this file. More onlocalbelow.name == nil or name == ""checks for no input at all, or an empty line.nilis Lua's "no value". In Lua, onlynilandfalsecount as false;0and""count as true, unlike in Python or JavaScript.if ... then ... endis how Lua marks a block: keywords, not braces or indentation...joins strings."Hello, " + nameis an error, because+is only for numbers.#nameis the length operator. On a string it counts bytes.utf8.len(name)counts characters in UTF-8 text.
Run it interactively and type your name:
lua5.5 greet.luaThen feed it names from a pipe, including one with accented letters and no input at all:
cd ~/hello-lua-demo
echo "Ada" | lua5.5 greet.lua
printf 'Ọlá\n' | lua5.5 greet.lua
lua5.5 greet.lua < /dev/nullThe difference between bytes and characters matters as soon as names are not plain English. The Yoruba name Ọlá has three letters but takes six bytes, because Ọ and á each need more than one byte in UTF-8. The same is true of Igbo, Amharic, Arabic or Swahili text with diacritics. If you check a length limit on a form or an SMS, use utf8.len, not #.
Check it worked
The first pipe prints What is your name? Hello, Ada! and then Your name is 3 bytes and 3 characters long. Ọlá gives 6 bytes and 3 characters. The empty input prints Hello, stranger!.
Step 6 · Use one table as a list and a map
Every collection in Lua is a table: a set of keys and values. When the keys are 1, 2, 3 and so on, the table acts as a list. When the keys are names, it acts as a map (a dictionary). One table can be both. Create table.lua:
cd ~/hello-lua-demo
cat > table.lua <<'LUA'
local city = { "Lagos", "Nairobi", "Accra" }
city.region = "Africa"
city.count_label = "cities"
print("First:", city[1])
print("Length:", #city)
print("Region:", city.region)
for i, name in ipairs(city) do
print(i, name)
end
for key, value in pairs(city) do
print("pair", key, value)
end
LUA
lua5.5 table.luaLine by line:
{ "Lagos", "Nairobi", "Accra" }is a table constructor. Values without keys get the keys 1, 2 and 3 in order.city.region = "Africa"adds a key calledregion.city.regionis shorthand forcity["region"].city[1]reads key 1, the first item. There is nocity[0].#citygives the length of the list part: 3. The two named keys do not count.ipairs(city)walks the list part in order, 1, 2, 3, and stops at the first missing number. It ignores named keys.pairs(city)walks every key, numbers and names alike, in no guaranteed order.printwith several arguments separates them with a tab.
Check it worked
You see First: followed by Lagos, Length: followed by 3, and Region: followed by Africa. The ipairs loop prints exactly three lines, 1 Lagos, 2 Nairobi, 3 Accra. The pairs loop prints five pair lines, and the order of the named keys may differ from run to run or machine to machine. If you need a fixed order, keep the names in a list and loop over that with ipairs.
Step 7 · Store a function in a local variable and avoid the 1-based trap
Functions in Lua are values, like numbers and strings. You can store one in a variable, put it in a table or pass it to another function. Create steps.lua:
cd ~/hello-lua-demo
cat > steps.lua <<'LUA'
local greet = function(who)
return "Hello, " .. who .. "!"
end
local names = { "Ada", "Kwame", "Zainab" }
print("Counting from 1:")
for i = 1, #names do
print(i, greet(names[i]))
end
print("Counting from 0, the way C and Python do it:")
for i = 0, #names - 1 do
print(i, names[i])
end
LUA
lua5.5 steps.lualocal greet = function(who) ... endmakes a function and stores it in the local variablegreet. Writinglocal function greet(who)does the same thing and is the more common spelling.returnsends a value back to whoever called the function.for i = 1, #names docounts from 1 up to and including the length. Both ends are included.- The second loop is the mistake people bring from other languages. It starts at 0 and stops one short.
Check it worked
The first loop prints three greetings: Hello, Ada!, Hello, Kwame! and Hello, Zainab!. The second loop prints 0 nil, then 1 Ada and 2 Kwame, and Zainab never appears. Lua does not raise an error for a missing key; reading it gives nil. When a list loop prints nil first and loses the last item, look for a loop that starts at 0.
A related trap: # is only reliable on a list without gaps. If you set names[2] = nil, the list has a hole and #names may answer 1 or 3; the manual calls any such answer a border. To remove an item from the middle of a list, use table.remove(names, 2), which shifts the later items down.
Step 8 · Catch global variable mistakes with a declaration
In Lua, a variable you assign without local becomes a global, visible to every file in the program. A misspelt name is not an error either; reading it gives nil. Lua 5.5 adds global declarations to catch this. Every file starts as if it said global * ("any unknown name is a global"). As soon as you write your own global line, that default is switched off and every name you use must be declared, either as local or global.
Create a script with a typo and run it:
cd ~/hello-lua-demo
cat > typo.lua <<'LUA'
local name = "Ada"
print("Hello, " .. tostring(nmae))
LUA
lua5.5 typo.luaIt runs and prints Hello, nil, because nmae is quietly treated as an unset global. Now add one declaration line naming the globals the file is allowed to use:
cd ~/hello-lua-demo
cat > typo-strict.lua <<'LUA'
global print, tostring
local name = "Ada"
print("Hello, " .. tostring(nmae))
LUA
lua5.5 typo-strict.lua || echo "exit code: $?"The rule of thumb for everyday Lua: write local in front of every new variable and function. Locals are faster, they cannot clash with another file, and a typo in one shows up quickly. Because global is now a reserved word, older code that used it as a variable name needs renaming before it runs on 5.5. Another 5.5 change: the counter in a numeric for loop is read-only, so i = i + 1 inside the loop is an error.
Check it worked
typo.lua prints Hello, nil. typo-strict.lua prints no greeting at all: Lua stops at compile time with an error on line 3 that names nmae and says it is not declared, then exit code: 1. Fix the typo to name and the strict version prints Hello, Ada.
Step 9 · Know where Lua is used, then clean up
Lua's size and C interface decide where it turns up:
- Games. Roblox (through its Luau dialect), Defold and many studio engines use Lua for game logic, because designers can change behaviour without recompiling the engine.
- Editors and tools. Neovim's configuration is
init.lua, and plugins are written in Lua. The Wireshark network analyser and the Pandoc document converter take Lua filters. - Servers. OpenResty builds Nginx with LuaJIT so request handling can be scripted, and Redis runs Lua scripts on the server. If you run Nginx (see install Nginx on Ubuntu 26.04), OpenResty is the Lua-enabled version of it.
- Devices. OpenWrt, the router firmware, has long used Lua for its LuCI web interface, and NodeMCU runs Lua on cheap ESP8266 and ESP32 boards.
All of these are hosts: a program written in C or C++ that creates a Lua state, hands it some functions and runs scripts against it. The lua5.5 command you used today is itself such a host, a short C program wrapped around the Lua library.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/hello-lua-demoKeep lua5.5 installed if you plan to carry on. To remove it, run sudo apt remove lua5.5.
Check it worked
ls ~/hello-lua-demo reports No such file or directory, and lua5.5 -v still prints the version until you remove the package.
Next steps
- Compare Lua's design with another general-purpose scripting language: Hello World in Python.
- Meet the other classic embeddable scripting language, built around strings instead of tables: Hello World in Tcl.
- Set up the web server that OpenResty extends with Lua: install Nginx on Ubuntu 26.04.
Related tutorials
- Hello World in Python: the interpreter, input and your first scriptYou will print Hello World in the Python 3.15 interpreter, save and run it as a script, greet a person by name from the keyboard and from the command line, and know what Python does with your file when it runs.
- Hello World in Tcl: tclsh, everything is a string, and TkYou will install Tcl 9.0, print Hello World from tclsh and from a script, read a name from the keyboard, and learn the three substitution rules that make up nearly all of Tcl's syntax.
- How to Install Nginx on Ubuntu 26.04You will install the current stable Nginx 1.30 from the official nginx.org repository on Ubuntu 26.04, serve its test page, and learn where its files live and how to reload it safely.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials