Skip to content
AgileLogics
4 min read

How Lua Code Runs

Prerequisites: Your first program

When you run lua hello.lua:

  1. Lua compiles the whole file into bytecode — compact instructions for the Lua virtual machine. Syntax errors are reported now, before anything runs.
  2. The virtual machine executes the bytecode from top to bottom.
  3. Runtime errors — like doing arithmetic on nil — stop the program when that line runs.

A syntax error

print("start")
if true
  print("inside")
end
lua: main.lua:3: 'then' expected near 'print'

Nothing printed — not even "start" — because the file failed to compile: if needs then. The message gives the file name and line number.

A runtime error

print("start")
local total = nil
print(total + 1)
print("never reached")
start
lua: main.lua:3: attempt to perform arithmetic on a nil value (local 'total')
stack traceback:
	main.lua:3: in main chunk
	[C]: in ?

This time "start" printed, then the error stopped the program. The stack traceback shows where it happened — useful when the error is deep inside nested function calls.

Precompiling

luac -o hello.luac hello.lua saves the bytecode to a file, which lua can run directly. It's mostly used to ship scripts without source or to check syntax (luac -p file.lua); bytecode isn't portable between Lua versions.

Embedded Lua

In a game or editor, the host program does these same steps through Lua's C API: it loads your script, runs it, and calls functions you define — for example, a function the game calls 60 times per second.