wolfhacklua API 1.1 Forum

Lua basics

Scripts are written in Lua 5.4. This page covers the parts you need to read and write them. Each example is a complete snippet you can paste into a script; log.info prints to the script's console.

Values and variables#

lua
local name = "wolf"        -- a string
local count = 3            -- an integer
local ratio = 0.75         -- a float
local ready = true         -- a boolean
local nothing = nil        -- nil means "no value"

log.info(name, count, ratio, ready, nothing)

Always write local when you create a variable. Without it the variable becomes a global, shared by every function in the script, which is a common source of bugs. A comment starts with --.

Lua has two number subtypes, integers and floats, and converts between them for you. 7 / 2 is 3.5; 7 // 2 is 3 (integer division); 7 % 2 is 1 (remainder); 2 ^ 3 is 8.0.

Strings#

lua
local who = "wolf"
log.info("hello " .. who)                  -- .. joins strings
log.info(#who)                             -- 4: # is the length
log.info(string.format("%d fps, %.1f ms", 144, 6.9444))
log.info(who:upper(), who:sub(1, 2))       -- methods use a colon

string.format fills in %d (integer), %.2f (float with 2 decimals), %s (string) and %02d (integer padded to 2 digits). It is the usual way to build text for the screen.

Booleans and conditions#

lua
local hp = 35
if hp <= 0 then
  log.info("dead")
elseif hp < 30 then
  log.info("low")
else
  log.info("fine")
end

local label = hp < 30 and "low" or "ok"      -- a one-line choice

Comparison operators are ==, ~= (not equal), <, <=, >, >=. Combine with and, or, not. In a condition only false and nil count as false; 0 and "" are true.

Tables#

The table is Lua's only container. It is a list, a dictionary and an object at once.

lua
local names = { "a", "b", "c" }            -- a list: indexes start at 1
log.info(names[1], #names)                 -- a  3
names[#names + 1] = "d"                    -- append

local player = { name = "x", health = 100 }   -- a dictionary
player.health = 80
log.info(player.name, player["health"])

Loop over a list with ipairs and over a dictionary with pairs:

lua
for i, v in ipairs(names) do log.info(i, v) end
for key, value in pairs(player) do log.info(key, value) end

ipairs goes in order from 1 and stops at the first gap; pairs visits every key in no particular order.

Functions#

lua
local function clamp01(x)
  if x < 0 then return 0 end
  if x > 1 then return 1 end
  return x
end

log.info(clamp01(1.7))        -- 1

Functions are values: you can store them in variables and tables and pass them to other functions. That is how events work: you hand the overlay a function and it calls it later.

lua
events.on("frame", function(dt)
  -- runs every frame; dt is the seconds since the last one
end)

A function can return several values: local w, h = app.screen_size().

Loops#

lua
for i = 1, 3 do log.info(i) end            -- 1 2 3
for i = 10, 1, -3 do log.info(i) end       -- 10 7 4 1

local n = 0
while n < 3 do n = n + 1 end

for _, p in ipairs(data.snapshot().players) do
  log.info(p.name)
end

break leaves a loop. Use _ for a value you do not need.

Scope and closures#

A local lives until the end of the block (do ... end, a function, an if). A function remembers the locals around it, which gives you private state:

lua
local function make_counter()
  local n = 0
  return function() n = n + 1; return n end
end
local next_id = make_counter()
log.info(next_id(), next_id())              -- 1  2

Most scripts keep their state in a few local variables at the top of the file and let the event handlers change them.

API 1.1 · source docs-src/pages/learn/lua-basics.md