Scripts, Text & Audio

Lua scripts

Give classes, races, skills, items, bonuses and creatures behaviour, and make game modes, in Lua 5.4 - every hook, the rta library, monster and game scripts, scripted skills, the sandbox, and the devkit's Lua Scripts module with its dry run.

A mod gives heroes, skills, items and creatures behaviour in Lua 5.4, and can run game modes. A mod's scripts are the files scripts/**/*.lua. Each file runs in its own environment and defines hooks: functions the game calls when something happens.

There are three kinds of script:

Kind Named by Runs
Hero scripts A class's script, a race's passive, a trait, a scripted skill, a designed skill's script, an item's or bonus's script For each hero that has it
Monster scripts A creature class's or kind's script For each creature of it
Game scripts Nothing: every file under scripts/game/ Once, for the whole game

Edit them in the Lua Scripts module, or make hero scripts as blueprints.

Hero scripts

Classes, races, skills and items name a hero script:

Where Key File
A class (heroes.toml) [class.N] script = "rage.lua" Its passive, for every hero of the class
A race (heroes.toml) [race.<code>] passive = "regen.lua" Its passive
A scripted skill (skills.toml) [script_skill.<name>] script The skill: can_cast, cast, and hooks while it is ranked
A designed skill (skills.toml) [design.<name>] script Hooks on top of the design (Skill Designer)
An item (items.toml) [item.<name>] script Runs while it is worn
A bonus (items.toml) [bonus.<keyword>] script Runs while an item with it is worn, the bonus's value as the rank
A trait (heroes.toml) [trait.<name>] script See Traits

Paths are under the mod's scripts/ folder.

Hooks

rank is the skill's rank: 1 for a class or race passive and a trait.

Hook Called when Returns
on_stats(hero, s, rank) The hero's statistics are computed. Change s.strength, intelligence, dexterity, stamina, max_health, max_energy, armor (added), s.damage, speed, health_regen, energy_regen (multipliers) and s.crit (added). Nothing
on_hit(hero, hit, rank) The hero's melee hit lands: hit.target, damage, element, crit The damage, or nil to keep it
on_hurt(hero, hurt, rank) The hero takes damage (after spells' defence): hurt.damage, element The damage, or nil
on_kill(hero, kill, rank) The hero kills: kill.target, experience, max_health, x, y, z Nothing
on_tick(hero, rank) Every simulation frame (60 a second) Nothing
on_level_up(hero, level, rank) A level is gained Nothing
can_cast(hero, rank) A scripted skill's button is pressed nil to cast, else the text explaining why not
cast(hero, rank) A scripted skill is cast Nothing
can_equip(hero, item, rank) An item is checked for wearing (in the inventory, the shop, equipping), after the class's own rules A string refuses with that text; true allows it over the class's rules; nil keeps their verdict
on_ammo(hero, ammo, rank) A bow's shot or a throw: ammo.kind ("arrows" or "thrown"), item, count, take The number it takes (0: free)
level_points(hero, points, rank) Levels are gained: points.levels, level, stat, skill Nothing (change points.stat and points.skill)
keep_item(hero, e, rank) A level script takes an item from the hero: e.item, level, reason true keeps the item

With can_equip, the item's level and statistic requirements still apply after it, and the first refusal of several scripts stands.

hero has level, cls, race, health, max_health, energy, max_energy, x, y, z, yaw, strength, intelligence, dexterity, stamina; hero:rank(name) (a skill's rank); and hero.data, a table kept per hero and file between calls. In a trait, hero.trait is its name and hero.params its parameters.

item (in can_equip) has name (lower case), slot and slot_name (one_handed two_handed shield body ring neck quiver gloves boots helmet leggings earring none), category, kind and kind_name (weapons: one_handed two_handed_sword two_handed_axe staff bow thrown), damage_type and damage (blunt piercing slashing), level, piece (an armour piece's type: its skin without the tier, chainbody, a mod's frogbody), and the flags weapon armor shield jewelry cloth bow thrown ranged two_handed.

Example The berserker's rage, as a class passive (script = "rage.lua").

function on_kill(hero, kill, rank)
  rta.buff(hero, "rage", 10, {damage = 1.25, speed = 1.1})
end

function on_hurt(hero, hurt, rank)
  if hero.health < hero.max_health * 0.3 then return hurt.damage * 0.8 end
end

A troll's regeneration, as a race passive (passive = "regen.lua"):

function on_tick(hero) rta.heal(hero, 0.02) end

Scripted skills

[script_skill.<name>] in skills.toml declares a skill whose behaviour is a script:

# gamedata/skills.toml (from the example-script example)
[script_skill.thunderclap]
id = 200                         # 192 and up. Saves keep it: always give it, never change it.
script = "example-script/thunderclap.lua"   # under scripts/ (default: <name>.lua)
title = "Thunderclap"
description = "Strike the ground: lightning damage and a short stun around you."
cost = [20, 3]                   # energy at rank 1, added per rank
s0 = [30, 12]                    # statistic 0 (damage here) at rank 1, added per rank
s1 = [180, 5]                    # statistic 1 (radius)
clip = "quake"                   # the hero's cast clip

[skill.1.17]                     # on the cleric's tree, like any spell
name = "thunderclap"
level = 6
requires = 16
-- scripts/example-script/thunderclap.lua
function can_cast(hero, rank)
  if #rta.enemies(hero, 250) == 0 then return "No enemies near" end
end

function cast(hero, rank)
  local damage = 30 + 12 * (rank - 1)      -- the same numbers as s0
  local radius = 180 + 5 * (rank - 1)      -- s1
  rta.area(hero, {radius = radius, damage = damage, element = "lightning"})
  rta.particles(hero, "dustcloud")
  for _, e in ipairs(rta.enemies(hero, radius)) do
    if rta.random() < 0.25 + 0.02 * rank then
      rta.status(hero, e.id, "stun", 1.5)
    end
  end
end

The keys: id (192 and up), script, passive (no button: only hooks), cost, s0 to s3 ([at rank 1, per rank], the skill's statistics), title, description, icon, ui_icon (its own square picture for NorrathUI and other interface mods; empty: they show icon in a ring) and clip.

Tip Try the Skill Designer first: most skills need no script. Its custom kind is a skill from scratch whose script reads properties you set there.

The rta library

Call Does
rta.random() The simulation's generator, 0 ≤ x < 1 (math.random is the same)
rta.log(text) A line in the game's log
rta.enemies(hero, radius) The enemies near, nearest first: {id, x, y, z, undead}
rta.heal(hero, n), rta.energy(hero, n) Health or energy, clamped
rta.damage(hero, target, n, element) Spell damage ("fire", "cold", "lightning", "poison", "disease", else plain)
rta.projectile(hero, opts), rta.area(hero, opts) A bolt or a blast: speed damage element radius life turn target x y z yaw visual (place and facing default to the hero's)
rta.particles(hero, name, [x, y, z]) A burst: blood dust goo dustcloud smoke ichor ice sparks puff spark burn, a number, explosion, or spell:<id>
rta.effect(hero, name, [x, y, z, yaw]) An effect, at the hero by default (a looping one runs one cycle)
rta.sound(hero, name) An fx.lmp entry, or "<lump>/<entry>"
rta.summon(hero, kind) A monster on the hero's side for 60 seconds
rta.status(hero, target, "stun" / "confuse" / "root", seconds) A status on a creature
rta.buff(hero, name, seconds, mods), rta.unbuff(hero, name), rta.has_buff(hero, name) Timed statistic changes (the on_stats fields); has_buff gives the seconds left, or nil
rta.achievement_add(who, counter, [n]), rta.achievement_max(who, counter, value), rta.achievement_unlock(who, id) Feed a counter of the mod's achievements or unlock one (who: a hero, a party slot, or nil for the party)
rta.skill(name, [rank]) A designed skill's keys and its own properties (.props), numbers at the rank (default 1), plus kind, id, rank; nil if there is none

Game scripts add more calls, which any script can use.

Monster scripts

A creature class or kind in monsters.toml names a script, and every creature of it runs the file's monster hooks. Set it in the Creature Editor, or by hand:

# gamedata/monsters.toml (from the example-monster-scripts example)
[kind.goblinshaman]
script = "example-monster-scripts/shaman_totem.lua"

A kind inherits its class's script, and script = "" turns it off for a kind.

Hook Called when
on_spawn(m) Its first frame in the world (placed, generated or summoned)
on_tick(m) Every simulation frame while it lives
on_hurt(m, amount) It lost amount health this frame (all blows together)
on_death(m) It died (its loot and experience are the game's as always)

m has id, kind, class, name, health, max_health, level, x, y, z, yaw, foe, boss, dead; target_hero (the player whose hero it fights) or target (the creature it fights); and m.data, a table of its own kept while it is in the world.

The hooks run after the creature's own step each frame, so its class code (its AI, attacks and role) runs as always and the script adds to it.

These rta calls take m where a hero script passes hero: rta.heal(m, n) (a negative n takes health, never below 1), rta.particles, rta.sound, rta.effect, rta.projectile, rta.area, rta.status and rta.summon(m, kind) (on the creature's side; returns the new creature's id). The monster calls:

Call Does
rta.play(m, clip, [loop]) Plays one of its clips by name; false if it has none
rta.set_max_health(m, n) Its maximum health (its health keeps its share)
rta.heroes(m, radius), rta.heroes(x, y, z, radius) The living heroes within reach, nearest first: {slot, x, y, z, health}
rta.blast(m, opts) Damage around a point, unblockable: radius damage element strength falloff x y z heroes monsters
rta.spawn(kind, x, y, z, [yaw], [allied]) A creature of that kind there, on the monsters' side (or the players' with allied); its id, or nil

Example A goblin shaman that chants to heal itself, calls for help and leaves fire behind.

local HEAL_EVERY = 4 * 60   -- frames between chants (60 a second)

function on_spawn(m)
  m.data.clock = math.random(HEAL_EVERY)   -- not every shaman chants on the same frame
  rta.set_max_health(m, m.max_health * 1.25)
end

function on_tick(m)
  m.data.clock = m.data.clock - 1
  if m.data.clock > 0 then return end
  m.data.clock = HEAL_EVERY
  if #rta.heroes(m, 400) == 0 then return end   -- only while it fights
  rta.heal(m, m.max_health * 0.1)
  rta.particles(m, "sparks")
  rta.play(m, "cast")
end

function on_hurt(m, amount)
  if not m.data.called and m.health < m.max_health / 3 then
    m.data.called = true
    rta.summon(m, "goblinrecruit")
  end
end

function on_death(m)
  rta.blast(m, {radius = 90, damage = 6, element = "fire", falloff = true})
  rta.particles(m, "explosion")
end

Game scripts

Every file under a mod's scripts/game/ is a game script: it runs for the whole game, like a game mode, with no data key naming it. Several mods' game scripts all run, in path order; a mod's file with the same path as another's replaces it.

Hook Called when
on_level_start(level) A level was loaded and its creatures placed: level.name, area_level, difficulty, players
on_tick() Every simulation frame
on_monster_spawn(m) Any creature's first frame in the world (after its own on_spawn)
on_monster_death(m) Any creature died (after its own on_death)
on_hero_death(hero) A hero fell: hero.slot, x, y, z
on_pickup(hero, item) A hero picked something up: item.name, text, category, quality (0 plain, 1 magic, 2 unique), or item.gold coins

m is the monster table above, so every call that takes a monster takes it. A game script's file-level locals last for the whole game: reset per-level state in on_level_start.

More calls, for any script:

Call Does
rta.announce(text, [seconds]) A message on the screen (3 seconds by default)
rta.monsters(m or hero, radius), rta.monsters(x, y, z, radius) The living creatures within reach, nearest first
rta.drop(m or hero, item), rta.drop(x, y, z, item) An item string on the ground there; false if it isn't one
rta.drop_gold(at, coins) A gold pile there
rta.drop_roll(at, tier) The game's own drop roll there at quality tier 0-9

Example A kill-streak bounty mode (from example-game-scripts).

-- scripts/game/bounties.lua
local STREAK_GAP = 20 * 60      -- frames without a kill before the streak ends
local streak, since_kill = 0, 0

function on_level_start(level)
  streak, since_kill = 0, 0
  rta.announce("Bounty hunt: " .. level.name, 4)
end

function on_monster_death(m)
  if not m.foe then return end
  streak = streak + 1
  since_kill = 0
  if streak % 10 == 0 then
    rta.announce("Killing spree! (" .. streak .. " kills)", 3)
    rta.drop_gold(m, streak * 10)
  end
  if m.boss then rta.drop_roll(m, 8) end
end

function on_hero_death(hero) streak = 0 end

function on_tick()
  if streak == 0 then return end
  since_kill = since_kill + 1
  if since_kill >= STREAK_GAP then streak = 0 end
end

The sandbox

Scripts run only where the simulation runs (single player, or the host of a network game), and other players see the results, so they never need syncing. The sandbox makes a script give the same results everywhere:

  • No io, os, load, require, dofile, collectgarbage, print, string.dump, rawget or rawset.
  • math.random is the simulation's generator.
  • pairs and next walk numbers ascending, then strings, then booleans (other key types are an error).
  • setmetatable refuses __gc and __mode; tostring of a table or function shows no address.

Each call has a budget of 2,000,000 instructions, and the whole state 64 MB. A script that errs is logged, and that call has no effect.

The Lua Scripts module

Lua Scripts (Scripts, Text & Audio section) has every scripts/**.lua of the mod in one place, tagged hero, monster (a creature's script names it, or it defines on_spawn or on_death) or game (under scripts/game/).

  • New makes a file from a template: a monster script, a game script (in game/), a hero passive or a scripted skill.
  • The editor checks the file in the game's sandbox as you type and lists the hooks it defines. A red file in the list doesn't compile.
  • Save writes the changed files (Ctrl+S saves all); Revert drops the edits.
  • Used by shows the lines of the mod's game data that name the file (script =, passive =...).
  • The reference lists the hooks and rta calls by where they work (hero only, monster only, both, game scripts).

Dry run calls the file's hooks on a stand-in game with no level, and lists every rta call it made and any error:

Script Dry run
Monster A goblin soldier at 100 health beside a hero: spawn, ten seconds of ticks, two hurts and a death
Game The level start, spawns, deaths and a hero's fall
Hero Statistics, a hit, a hurt, a kill, ticks and a cast

Validate lists scripts that don't compile and those that define no hook. Opening a .lua from the Content Browser or Find in Mod opens it here.

Note Save waits while another editor has unsaved work, since the Class & Race Editor keeps its own copies of the scripts it shows and writes them when it saves.

To try a script in the game, see Testing.

Examples

example-script (a scripted active and passive skill), example-monster-scripts (the goblin shaman), example-game-scripts (the bounty mode) and example-traits. See Examples.