Mod scripts
A mod's boss can be driven by a short Lua script. The boss kit (docs/HOWTO-CONTENT.md, "A boss
kit") says which abilities a boss uses and how often; a script says which one, and when,
by reading how the fight stands. This guide is the whole API. The data words that name a script
are in docs/HOWTO-CONTENT.md, "A scripted ability"; what a script may return are the abilities
of that file, so read "A boss kit" first.
What a script is, and where it runs
- A script is Lua 5.1 in a sandbox. It cannot reach your files, the network, the clock or the
game: it gets a
ctxof plain numbers, astateof plain data it kept from its last call, and it returns commands (abilities to play, lines to yell) and thestateto keep. - Only the host runs it, and only in the native game. In co-op the host's game plays the
bosses; a guest sees what it is sent and never runs a script. The browser build has no scripts:
it refuses a scripted mod before anything starts (the capability
scripts-v1, below). - No official pack has scripts. A scripted mod is Modded like every mod: heroes and progress of its own, no cloud saves, no ranks, co-op only on exactly the same lock. The Mods window marks it with a Scripts badge and asks a second time before it is chosen.
- A script runs on the player's computer, so a package with scripts is reviewed as source (see
"Publishing a mod" in
docs/HOWTO-CONTENT.md).
The files
- A script is the file
packs/<package id>/scripts/<name>.luaof your package, a locked object of the kindscript. The name is lower case letters, digits,_and-. UTF-8, no NUL byte (a byte order mark is dropped). At most 64 KiB a file, 16 files a package, 1 MiB of scripts a profile. - A profile with a script requires the capability
scripts-v1inprofile.json(azs-release profile-lockwrites it). A game without it refuses the import and says why. - A boss kit names a script:
[[boss.kit]] every = 8.0 ability = { script = { name = "slam", params = { reach = 4.0 } } }
When the entry comes due (every) the script'sfirehook runs.params(at most 16, finite numbers) are numbers your script reads asctx.params.reach. Several entries may name one script with different params. - A phase names a script with
script = "<name>"on a[[boss.phase]]: itsphasehook runs as the boss takes that phase up. - Where a name resolves. In the pack that defines the boss kit file, never in another pack. A script is no step of a combo, and an elite's kit (a zone's lair guardian) cannot call one: the import refuses it, naming the elite and the script.
- Yells. A script may have the boss say a line of its kit file's
[boss.yells.<id>], a text in all twelve languages like a phase'syell. A script cannot make up a line.
The hooks
A script defines up to three global functions at its top level. Each is called as
hook(ctx, state) and may return commands, state.
state is always a table: empty at a boss's first call, after that a copy of the state kept last.
A phase or death can come before any fire (a boss can fall in one blow), and the check calls
every hook with an empty state too, so a hook must not count on a field another hook sets: write
(state.casts or 0), never state.casts + 1.
fire(ctx, state): a kit entry that names the script comes due.ctx.eventisnil.phase(ctx, state): a phase that names the script begins.ctx.eventis the phase number as text:"1"for the first phase after the opening one.death(ctx, state): the boss falls; called once for every script its kit and phases name, in name order, after which the boss's state is forgotten.ctx.eventis"death". It may returnsaycommands only.
A phase or death hook the script does not define is not called. A fire hook it does not
define is an error each time (see "Errors"). When several hooks are due in one step they run
sorted by boss, a boss's phase before its fire, fire in kit order.
The top level of the file runs afresh before every call, in a new environment: a local there
(like nova in the example) is rebuilt each time and keeps nothing. What lasts between calls is
the state, and nothing else. Assigning a global from inside a hook is an error
(a script cannot set the global 'x'): keep what lasts in the state.
ctx
Plain numbers, a fresh table at every call:
| Field | Meaning |
|---|---|
ctx.time | the run's clock, in seconds |
ctx.tier | the difficulty tier, from 0 |
ctx.boss.hp_share | the boss's health, 0 to 1 |
ctx.boss.phase | the boss's phase, 0 in the opening one |
ctx.boss.x, y, z | where the boss stands |
ctx.boss.facing | the direction from the boss to its nearest hero, in radians |
ctx.boss.adds_alive | how many ordinary enemies are alive |
ctx.heroes[i] | up to five heroes that are in the fight, in seat order: x, y, hp_share. The list can be empty: look before you read ctx.heroes[1] |
ctx.params | the params of the kit entry that named the script (empty for phase and death) |
ctx.event | nil for fire, the phase number as text for phase, "death" for death |
ctx.roll() | the next number, 0 up to (not including) 1, of the run's script random stream |
What a hook returns
return commands, state. Both are optional.
commands: a list (keys 1 to n, no holes) of at most 8 commands, ornilor{}for none.state: the table to keep for the next call (see "State"). A hook that returns no second value keeps the old state;return commands, nilclears it.
Commands
{ say = "<id>" }: the boss yells the English line of[boss.yells.<id>]. No other field.{ ability = <ability>, delay = <seconds> }: plays an abilitydelayseconds from now.delayis optional (0) and is 0 to 30.<ability>is the table a kit writes afterability =, in Lua:{ nova = { spell = 905193, radius = 9.0, warn = 2.0 } },{ adds = 5 },"charge". It goes through the kit's own number checks, and one more: an ability with awarngives at least 1.0 second of warning (a script can read where the heroes are, so a hit it places must be one a hero can still step out of).{ ability = { combo = { { <step>, ... }, <gap> } }, delay = <seconds> }: a combo as the kit'scombois: 1 to 8 steps,gapseconds apart (0 to 10), the firstdelayseconds from now. The ability table holdscomboand nothing else; a step is no combo and no script.- A command with any other field is refused.
deathmay onlysay. - Numbers go by value, so
4and4.0are the same. A command table may share a sub-table with another (the example'snova(radius)builds a fresh one each time anyway).
State
The state is what a script remembers, kept per boss and per script name (a boss that dies takes
it with it), and carried through checkpoints and a host handover. It is nil or a table of:
nil, booleans, finite numbers, strings, and tables of those;- table keys that are numbers or strings;
- no functions, no table with a metatable, and no table held twice (a cycle or two keys naming one table): copy it instead.
At most 4 KiB once encoded and 16 levels of tables (the state itself is level 1). The state a hook receives is a copy: a change reaches the next call only through the returned state. A returned state that breaks a rule fails the call (see "Errors"), which keeps the old state.
The sandbox
What exists:
- Base:
assert,error,ipairs,next,pairs,select,tonumber,tostring,type,unpack(at most 250 values: more is an error). string:len,byte(at most 250 values),char,sub,upper,lower(ASCII only),rep,format(only%d,%s,%fand%%, no widths, at most 32 values). Strings take the method form,("x"):upper(). The bounds ofunpackandstring.byteare truncated toward zero, and NaN reads as 0.math:abs,ceil,floor,max,min,sqrt,fmod,huge,pi,sin,cos,exp,log,atan2,pow.table:concat,sort,insert,remove.table.sortis a stable merge sort: elements that compare equal keep their order, and a comparator that is not consistent gives some order, never an error. Every comparison is counted as fuel: a sort of 1,000 numbers costs about 140,000 of a call's 200,000.
Nothing else exists: no pcall or xpcall (a script could catch the out-of-fuel error and go
on), no math.random (use ctx.roll()), no os, io, require, load, loadstring,
dofile, getmetatable, setmetatable, rawget, rawset, no string.find, match, gsub,
gmatch or dump, no table.getn. The library tables cannot be written to. The ^ operator is
refused when the script loads: write math.pow(x, y).
Limits
Every number, as the game enforces it:
| What | Limit |
|---|---|
| VM instructions one hook call may run (the fuel) | 200,000 |
| VM instructions all the calls of one simulation step may run together | 1,000,000 |
| Memory the VM may hold | 8 MiB |
| Commands one call may return | 8 |
| A call's command list, read as data (a table held twice counts twice) | 64 KiB |
delay of a command | 0 to 30 s |
Steps of a combo | 1 to 8 |
gap of a combo | 0 to 10 s |
Warning (warn) of a script's ability | at least 1.0 s |
| State, encoded | 4 KiB |
| Levels of tables in the state | 16 |
params of a kit entry | 16 |
| One script file | 64 KiB |
| Script files of a package | 16 |
| Script files of a profile | 1 MiB together |
Values one unpack or string.byte returns | 250 |
Fuel is counted in steps of 1,000 instructions. Work that one instruction or one library function
does in proportion to its operands is charged on top, before it is done, one instruction for every
32 bytes: the bytes .. copies, both lengths of a string <, <=, > or >=, 16 bytes for each
value a ... expands to where all its values are taken (f(...), {...}, return ...; not
local a, b = ...), 1 byte for each array slot and 3 for each node of a table that rehashes (the
store that finds a full table; a rehash that shrinks the array part also pays 3 for each slot it
moves into the hash part), and what rep, format, concat, sub, upper, lower, pairs,
next and tonumber copy or scan. A table that grows because a constructor sizes it ({ ... },
{ 1, 2, 3 }) is not charged. So a .. b of two 100,000-byte strings costs 6,250 fuel, while
short strings cost next to nothing, and the growth of a table to 100 string keys costs 12. A
string.rep, string.format or table.concat that would pass the memory limit is an error at
once. azs-script check also warns when a script holds more
than half the memory.
Determinism
Every machine must play the same fight from the same seed. The sandbox keeps it so; a script that depends on anything else is refused by the check.
pairsandnextwalk a table in a fixed order: number keys ascending, then string keys in byte order. A table keyed by a table, a function or a boolean has no order, and walking it is an error.- Strings compare by their bytes, as unsigned numbers, whatever the computer's language settings:
"Z" < "a","a" < "a\0", andtable.sortwithout a comparator sorts strings so. tostringof a table or a function is an error (it would print an address).- Chance is
ctx.roll(), the run's ownscriptstream, drawn only when you call it. There is no clock:ctx.timeis the run's. - The same
ctxandstatemust give the same commands, state and fuel. The check calls every hook twice in two VMs to see that.
Errors
None of these ends the run.
- A hook that raises an error, runs out of fuel or memory, returns commands that break a shape rule
(more than 8, an unknown field, a
delayorgapout of range, a combo of the wrong shape, an ability table the kit would not read) or returns a state that breaks a rule fails: it gives no commands, keeps the old state, and is counted and logged. The third failure of one script on one boss switches that script off for that boss until the fight ends; the boss goes on with its other kit entries. - A single command that is well formed but may not play (its numbers fail the kit's checks, its
warnis under 1.0 s, it is not asayindeath, or it names a yell the boss kit does not define) is dropped: the rest play. Drops are counted; the first three of each script on each boss are logged. - A script that does not load (a syntax error, or a top level that fails) is logged once and none of the profile's scripts runs.
Checking a profile
azs-script check <profile folder>
It resolves the profile as azs-content profile-check does, then runs every script a boss kit or
phase names: it loads, calls every hook the kit uses it through (and death when defined) against
30 fixed fights (the boss at 100, 75, 50, 25 and 5 % health, each with 0 to 5 heroes, and every
params set of the kit entries that name it), calls each hook twice in two VMs, and then calls
each 200 times in a row with its state carried over. It prints one line per problem,
packs/<package>/scripts/<name>.lua:<line>: <message> (no line when the VM has none), and exits
1 when there is any; with none it prints azs-script: <folder>: N script(s) checked, no problems
and exits 0. The game runs the same check when a profile with scripts is imported. A problem is one
of:
a boss kit names the script ... but ... does not exist: no file at that path in the pack that defines the kit file.... is not a script name: a name that breaks the rule above.- A syntax error with its line, or the
^operator message, or a top level that fails. loads alone but not together with the profile's other scripts: the game loads every script of a profile into one VM, whose 8 MiB they share; the first script that does not fit is named.a boss kit calls its ... hook, which the script does not define.... gave different results in two identical calls: the script depends on something other thanctxandstate.- An error of a hook, named with the fight it met (
0 hero(es), boss at 100% health) and its line: a nil index, out of fuel, out of memory, a bad command list. - A command problem:
says x, but boss b has no yell x in its kit file(each boss that uses the script is checked on its own, as the run does),warn = ... is under the 1 s of warning a script's ability must give,death may return say commands only, or the kit's own number check of the ability. ... after chained calls: bad state ...: the state outgrows its limits when a hook's state is fed back to it (the 200 calls).uses about N KiB, more than half the 8 MiB limit.a call took N ms; a slow script freezes the game while it runs(orits calls took N ms together): one call took more than 250 ms, or all calls of one use of the script more than 10 s (each use starts from zero).its top level took N ms; a slow script freezes the game while it loads: loading the script (running its top level) took more than 250 ms, a bound of its own (CHECK_LOAD_SLOW). In each case the script is checked no further. These are wall-clock limits of the check only; the game has no clock in a run.
A worked example
A boss that slams a nova every 8 seconds, and on every third slam a combo of three growing novas
and a yell; it yells once more as it dies. Appended to a boss kit file, packs/<package>/bosses/<boss>.toml:
[[boss.kit]]
every = 8.0
ability = { script = { name = "slam", params = { reach = 4.0 } } }
[boss.yells.slam]
en = "Slam!"
de = "Wumms!"
fr = "Boum !"
es = "¡Zas!"
pt = "Pancada!"
ru = "Бам!"
it = "Bum!"
pl = "Trzask!"
tr = "Güm!"
ja = "ドン!"
zh = "砰!"
ko = "쾅!"
and packs/<package>/scripts/slam.lua:
-- slam.lua: a nova on every cast, and on every third cast a combo of three novas and a yell.
local function nova(radius)
return { nova = { spell = 905193, radius = radius, warn = 1.5 } }
end
function fire(ctx, state)
local casts = (state.casts or 0) + 1
state.casts = casts
local radius = (ctx.params.reach or 4) + 2 + ctx.roll() * 2
if casts % 3 == 0 then
local steps = { nova(radius), nova(radius + 2), nova(radius + 4) }
return { { ability = { combo = { steps, 1.5 } } }, { say = "slam" } }, state
end
return { { ability = nova(radius), delay = 0.5 } }, state
end
function death(ctx, state)
return { { say = "slam" } }
end
crates/survivors-script/tests/guide.rs holds both files verbatim (tests/example/) and runs
the check on a profile built from them, so this example cannot go stale.
Known limits
These are accepted for the first version, and an author should know them.
- How long a call can hold the host. The instructions that do work in proportion to their
operands pay for it in fuel (see "Limits"):
.., string comparison,..., a table's rehash, and the library functions.unpackandstring.bytereturn at most 250 values, andtable.sortis a merge sort whose comparisons are counted, so no order of the elements makes it slow. The work the meter and the library charge is therefore at most about 6.4 MB per call (200,000 fuel at 32 bytes); for rehashes that figure is nominal, since a node is charged at a fixed 3 bytes, far under its real size, and the measured times below are the bound. Measured on Windows 11 in a release build, each of these loops ends in fuel: comparing two 2 MB strings 1 ms (20 s before the meter), concatenating a 512 KiB string with itself 1 ms (1.6 s before),unpack(t, 1, 250)7 ms (28 ms before; a 7,000-valueunpacktook 0.7 s and is now refused),string.byte(s, 1, 250)1 ms, a 7,000-value...0 ms (0.17 s before),table.sortof a 12,000-element order crafted against the old quicksort under 1 ms (0.4 s before), removing and inserting keys of a full 32,768-key table, which rehashes it each time, 20 ms (9 s before), and the same beside a 32,768-slot array 2 ms (0.2 s before). A table whose array part shrinks and grows again at each rehash is charged by the rule in "Limits", but its worst case was not measured. Some work is not charged: copying a C function's results (a 600-value...through 95 nestedselectcalls, 6 ms), the garbage collector, and long chains of keys that collide in a table. The game has no clock (a clock would break determinism); the author check and the import check still time every call and every load, and a script one call or top level of which takes more than 250 ms (or all its calls in one check more than 10 s) is reported and checked no further. - Hash collisions. Lua 5.1 hashes strings and numbers without a secret seed, so a script can
build keys that all land in one chain of a table (or of the VM's string table). Each new key or
lookup then walks the chain inside one instruction, and fuel does not see that work: it grows
with the square of the number of such keys. How long one call can hold the host this way is not
measured yet. The author check reports such a script only after the call returns; it cannot stop
a call. The defence for now is the registry's review of the source. A fix needs a keyed hash in
the
lua-srcfork, and it is not done. - Numbers as text.
..and a number passed where a string is wanted (string.upper(0.5)) use the C library's%.14g, which prints every finite number alike on the supported platforms and differently for NaN and the infinities. Never concatenate a number that may not be finite.tonumberreturnsnilfor a result that is not finite, but a non-finite number can still come from arithmetic (1/0,0/0), from a string turned into a number by arithmetic or a comparison ("inf" + 0,"1e999" + 0), and from a literal too large to hold:1e999in the source is infinity. - Near the memory cap. A script that holds close to the 8 MiB can fail on one VM and not on another: the VM that has run the fight so far holds garbage a VM built fresh after a host handover does not. That is why the check warns at half the cap; stay well under it.
- Two spellings of a number.
tostringandstring.formatprint the shortest text that reads back as the same number,..prints 14 significant digits:tostring(0.1 + 0.2)is0.30000000000000004,"" .. (0.1 + 0.2)is0.3. Pick one and keep to it. - No
^. The operator is refused when the script loads; usemath.pow(x, y). - Scripts run in bosses' kits only. A script in an elite's kit is refused at import; only boss kits and phases call scripts.
- A script is code. It cannot leave its sandbox, but it runs on the player's computer, so the registry's reviewers read it as source, and a review is no promise.
