Practical Lua
Guard clauses and early returns#
Handlers run every frame, so the first lines should leave quickly when there is nothing to do:
events.on("draw", function()
local snap = data.snapshot()
if not snap.in_game then return end
local me = snap["local"]
if not me then return end
draw.text(20, 20, 0xFFFFFFFF, "health " .. me.health)
end)Tables as records and settings#
Keep related values in one table and give the defaults in one place:
local DEFAULTS = { size = 14, show = true, corner = "top-right" }
local function setting(name)
local v = store.get(name)
if v == nil then return DEFAULTS[name] end
return v
end(In practice store.get(name, default) does this for you.)
Building and sorting lists#
local near = {}
for _, p in ipairs(data.snapshot().players) do
if not p.teammate and p.health > 0 then near[#near + 1] = p end
end
table.sort(near, function(a, b) return a.distance < b.distance end)
local names = {}
for i, p in ipairs(near) do names[i] = p.name end
log.info(table.concat(names, ", "))table.insert(t, v) and table.remove(t, i) work as expected; table.concat(list, sep) joins strings, and table.unpack(t) spreads a list into arguments.
Handling errors#
A raised error inside a handler is caught by the host, written to your console with a traceback, and counted; the script keeps running. You can catch an error yourself with pcall:
local ok, result = pcall(function()
return json.decode(text).items[1].name
end)
if not ok then
log.warn("bad data: " .. tostring(result))
endRaise your own with error("message") and check inputs with assert(value, "message").
Many API functions report failure as a value instead of raising: file.read returns nil, err, json.decode returns nil, err, memory reads return nil. Check the return value.
Coroutines and tasks#
A coroutine is a function that can pause and be resumed later. The host builds on them as tasks, so you write sequential code without callbacks:
task.spawn(function()
log.info("start")
task.wait(2) -- pause for two seconds
log.info("two seconds later")
for i = 1, 5 do
log.info("step " .. i)
task.yield() -- give the frame back, continue next frame
end
end)task.wait, task.yield and task.await only work inside a task. See task.
Splitting code into modules#
In a folder script, put helpers in their own file and require them. A module is a file that returns a table:
local M = {}
function M.clock(sec)
sec = math.floor(sec)
return string.format("%02d:%02d", sec // 60, sec % 60)
end
return Mlocal format = require("format")
log.info(format.clock(125)) -- 02:05require caches a module: the file runs once and later calls return the same table. See script folders.
Avoid creating garbage every frame#
Allocating tables and strings inside a draw handler works, but it makes the garbage collector work harder. Build constant tables once at the top of the file, reuse them, and compute text only when it changes. Performance has the numbers.