Installation, Tools and First Program

2.1 Installing Lua

# Linux
sudo apt install lua5.4 liblua5.4-dev luarocks     # Debian/Ubuntu
sudo dnf install lua lua-devel luarocks            # Fedora
# macOS
brew install lua luarocks
# Windows: LuaBinaries (luabinaries.sourceforge.net), scoop install lua, or choco install lua
# Build from source (any platform with a C compiler)
curl -L -R -O https://www.lua.org/ftp/lua-5.4.7.tar.gz
tar zxf lua-5.4.7.tar.gz && cd lua-5.4.7
make all test && sudo make install
# LuaJIT
git clone https://luajit.org/git/luajit.git && cd luajit && make && sudo make install
# Version managers: hererocks (pip install hererocks), luaver, luaenv
lua -v

2.2 Hello, World

-- hello.lua
print("Hello, World!")

local name = "Lua"
print("Hello, " .. name .. "!")          -- .. concatenates strings
print(string.format("Version: %s", _VERSION))
lua hello.lua
lua -e 'print(2 ^ 10)'                   # execute a string
lua                                      # interactive REPL (Ctrl+D / Ctrl+Z to exit)
lua -i script.lua                        # run the script, then enter the REPL
lua -l module script.lua                 # require a module first
luac -o hello.luac hello.lua             # compile to bytecode
luac -l hello.lua                        # list bytecode

2.3 Lexical Basics

Keywords (22): and break do else elseif end false for function goto if in local nil not or repeat return then true until while.

Identifiers are case-sensitive. Names starting with an underscore followed by uppercase letters (like _VERSION, _ENV) are reserved by convention.

A chunk is a sequence of statements (a file or a string). Chunks are compiled as anonymous functions with varargs.

A shebang line is allowed: #!/usr/bin/env lua.

-- Single-line comment
--[[ Multi-line
     comment ]]
--[==[ Comment that can contain ]] inside ]==]

local a = 1; local b = 2                 -- semicolons are optional
local c = 3 local d = 4                  -- statements can share a line

2.4 Editors and Tooling

VS Code + Lua Language Server (LuaLS: completion, diagnostics, type annotations), the Local Lua Debugger extension

Neovim (built-in Lua), ZeroBrane Studio (Lua IDE with a debugger), IntelliJ + EmmyLua

StyLua (formatter), luacheck / selene (linters), busted (testing), LuaRocks (packages)