Nanfeng

Notes on software development, code, and curious ideas

Getting Started with Lua

The traditional first Lua program is one line:

1
print("Hello, world!")

Save it as hello.lua and run it with the standalone interpreter:

1
lua hello.lua

Lua is also designed to be embedded, so many people run scripts inside a game engine, application, or device rather than through the standalone command.

Basic syntax

Statements do not require semicolons. A line beginning with -- is a comment, and --[[ ... ]] forms a block comment.

1
2
3
4
5
6
local name = "Lua"
local version = 5.4

if version >= 5.0 then
print(name .. " is ready")
end

Names are case-sensitive. A variable is global unless declared local; prefer locals to keep dependencies and scope clear.

Values

Core types include nil, boolean, number, string, function, table, thread, and userdata:

1
print(type(nil), type(true), type(42), type("text"))

Only false and nil are false in conditions. Zero and empty strings are true.

Functions and tables

1
2
3
4
5
6
7
8
9
10
11
12
local function greet(person)
return "Hello, " .. person
end

local users = {
{ name = "Ada", active = true },
{ name = "Lin", active = false }
}

for _, user in ipairs(users) do
if user.active then print(greet(user.name)) end
end

The interactive interpreter is useful for experiments. Enter expressions through print, inspect values with type, and exit using the platform’s end-of-file shortcut. For real programs, organize code into modules that return explicit tables instead of relying on globals.

+