Skip to content

The Lua Runtime

When the port runs a mod's scripts, what a script may do, and what happens when it fails.

Lifecycle and event order

obm.on(event, fn) registers a listener. The events:

Event Arguments When
init none After every active mod's entry file has run, at startup and after each reload
shutdown none Before the Lua state is closed, at exit and at the start of each reload
hot_reload scene name After a reload (F6, obm.reload() or the console button), when a scene is loaded, before scene_loaded
scene_loaded scene name The first frame a scene is loaded: menus, the Hideout and missions alike
scene_unload scene name When the loaded scene goes away or changes, before the next scene_loaded
frame dt Every frame while a scene is loaded, before the engine updates the world
hud_draw none Every frame while the HUD is drawn; the only time obm.hud drawing functions draw
ui_draw none Every frame while obm.ui.set_visible(true) is in effect; the only time obm.ui widgets work
actor_killed actor table, or the ref when the object is not an actor; and the kill (below), or nil When the level control records a death
weapon_fired weapon ref When 47 fires
mission_outcome "complete" or "fail", the failure's locale key ("" for a completion) When the level control ends the mission (MissionCompleted or MissionFailed), before custom mission rules can suppress it
cheat_menu none When the player presses the game's cheat-menu key (C in the PC layout), which opened the PC version's cheat menu
movie_start movie name, is_intro When a movie is about to play: the file's base name without extension ("Eidos", "M00_Intro"), and whether it is one of the logo movies before the main menu. obm.movies.skip() here skips it.

The kill table of actor_killed says how the person died, from what the game itself records (ZHM3LevelControl::WeaponUsed, the victim's last damaging weapon and its accident flag):

Field Meaning
cause "accident", the weapon's item class (fiber_wire, poison, pistol, smg, shotgun, rifle, sniper, melee, explosive, sedative...; see Item classes), or "unknown" when nothing was credited
weapon, weapon_class The weapon's template name and class, or ""
accident The game counts the death as an accident (a push, a fall, a rigged object)
by_47 47 caused it (his weapon, or an accident)
headshot The killing shot hit the head
disguise, disguise_suit The outfit 47 wore at that moment (obm.player.outfit().name), and whether it was his own suit

Scene names are base names, such as "M05_Main" or "Hideout_Main". dt is the engine's frame time in seconds: 0 while the game is paused, and at most 0.25.

Listeners of one event run in the order they were registered, which is the load order of the mods.

Startup

  1. The mod manager scans the mods folders and reads the mods section of obm.config.json (before the launcher opens).
  2. When the game starts, the runtime creates the Lua state and runs the entry file of each active mod, in load order. Code at the top level of an entry file runs here, before any scene exists: obm.world functions return nothing useful yet.
  3. init fires.

Each frame

  1. A reload requested by obm.reload() or the console's button happens here.
  2. Key states are read; obm.input.just_pressed is true for this frame for keys that went down since the last frame. Binding and gamepad button states are read, and the highlights of the last frame are cleared.
  3. If no scene is loaded: if one was, scene_unload fires and the scene state is reset (below). Nothing else runs this frame.
  4. If the scene is new: scene_unload for the old one if there was one, then scene_loaded.
  5. The runtime systems update: solid props push 47 out, ghost recording and playback, actions (an action's callback runs here when its key is pressed), projectiles (their on_hit callbacks run here), allies and enforcers, dynamic lights and patrols.
  6. frame fires.
  7. The engine updates the world. During this step, replaced scripts resume, obm.scripts.on_message and obm.scripts.hook_api handlers run as the .c scripts send messages and call interfaces, and actor_killed and weapon_fired fire.
  8. While the frame is drawn: hud_draw, then ui_draw.

When a scene goes away

scene_unload fires first. Then the runtime resets, for every mod: custom mission rules, a pause from obm.time.pause, the time and look scales, the FOV scale, camera shake and the camera override, the light tint, blackout and flashlight, weather, the dialogue line, actions, ghosts and the ghost recording, patrols, the atmosphere grade, the shader, model replacements, props, projectiles, draw3d shapes, dynamic lights, and enforcer and ally tags. The coroutines of replaced scripts, the obm.scripts.list() records and the copies of strings passed to obm.api go when the scene's script module unloads, which the engine does before the next scene's scripts load.

These stay until the mod changes them or the mods reload: difficulty overrides, hidden vanilla HUD elements, obm.ui visibility, audio voices, music layers and the pitch, the network socket, the active contract, disabled-script entries, script replacements, message and API hooks, and every listener.

Reloading

F6 reloads at once: shutdown fires, the Lua state is closed, the mods folders are scanned again, every active mod's entry file runs in a new state, init fires, and, if a scene is loaded, hot_reload and then scene_loaded fire with its name. scene_unload does not fire. obm.scripts.list() still lists the loaded scene's scripts, but a script replacement only takes effect when a script loads, so it applies from the next scene. Lua values do not survive; keep what must survive in obm.storage.

obm.reload() and the console's Hot-Reload All Mods button do the same at the start of the next frame.

Level missions

A custom level's mission (in its levels entry) is a Lua file that runs only while that level is played. The runtime loads it with the first script of the level's scene, when the active custom level (obm.level.active()) has a mission and the scene loading is its base_scene, so the mission is in place before scene_loaded and before the scene's scripts start, and an obm.scripts.replace it makes applies to them. A level mod needs no entry for this.

  • It runs in an environment of its own: its globals are its own, and reading a name it has not set falls back to the mod's environment (obm, require, the mod's own globals).
  • Everything it registers, and everything its callbacks register later (listeners, obm.scripts.on_message and hook_api hooks, script replacements, disabled scripts), belongs to the mission. When the level's scene goes (after its scene_unload), or another scene's scripts load, the runtime removes all of it and logs mods: level mission <file> of '<level>' unloaded (N registrations removed).
  • A restart loads it afresh. A hot reload (F6) runs it again in the new state, before hot_reload and scene_loaded fire; as for any replacement, a script it replaces stays the original until the scene loads again.
  • require from a mission loads the module into the mod's environment, where it stays cached: register listeners in the mission file or in functions it calls, not at a module's top level.

The mission library (obm.mission.define) is written for these files; Mission scripting is its reference.

The Lua environment

Mods run in Lua 5.5.1, in one Lua state shared by all mods, created at game start and kept across scene loads (it is not part of the game heap).

Each mod has its own global environment: its own _G, its own copies of the standard library tables and its own obm table. A mod cannot read or change another mod's globals or replace another mod's functions, and there is no supported way to pass Lua values between mods. Mods can still affect each other through shared game state (two mods setting the time scale, or the difficulty overrides, see below).

Libraries:

Library Available
base Yes, without dofile and loadfile. load takes text chunks only; a binary chunk is refused. print writes to the SDL log and the F12 console, tagged with the mod id; warn shows in the console. collectgarbage accepts only "collect", "count", "step" and "isrunning", since the heap is shared. setmetatable rejects metatables that have a __gc field.
coroutine, table, utf8, math Yes
string Yes, without string.dump. The string metatable is locked: getmetatable("") returns false.
io, os, package, debug No

Entry files and required files must be Lua source; precompiled files are refused.

require(name) loads a module from the calling mod's own package. Dots in the name become / and .lua is added; the file is looked up as scripts/<path>.lua first and then <path>.lua, both relative to the folder that holds mod.json. require("ai.patrols") loads scripts/ai/patrols.lua. A name containing .. is refused. The module's result is cached per mod, so a second require of the same name returns the same value.

Instruction budget

Each call from the engine into Lua gets 500,000 Lua VM instructions. A call from the engine is one event listener, script message or API hook, action callback, projectile on_hit, resume of a replaced script, replaced script's message handler, or console line, and the budget covers everything it calls. Callbacks that run inside it (an engine hook the callback triggers) share the same budget.

When the budget runs out, the callback is aborted with the error instruction limit exceeded. pcall cannot catch it and continue: every further instruction raises the error again until control is back in the engine. A long job should be split over frames, for example in a coroutine resumed from frame.

Lua disables debug hooks while running __gc finalizers, so the instruction budget cannot interrupt a loop inside one. For that reason, setmetatable refuses any metatable that has a __gc field.

The budget counts Lua VM instructions. A library function written in C runs whole once called and counts as one instruction. string.find, match, gmatch and gsub with a pattern that backtracks heavily ((".-"):rep(10) .. "x" against a long string without an x) take time that grows with the string's length to the power of the number of .- and .* items, and can hold the frame for minutes.

Memory

All mods share one Lua heap of at most 256 MB. An allocation beyond it raises not enough memory in the mod that asked for it.

Error behaviour

  • A syntax error in an entry file stops that mod's file from running; other mods load normally.
  • An error while an entry file runs stops the rest of that file. Listeners it registered before the error stay registered.
  • An error in a callback ends that call. The error is logged with the mod id and the context (the event name, action, hook_api and so on): the SDL log gets the message with a stack traceback, the F12 console its first line. The next call runs normally.
  • A listener, hook, action or coroutine that raises 5 errors is switched off until the next reload, with a message in the console. Other callbacks of the same mod keep running.
  • A replaced script whose coroutine raises an error, or returns, stays stopped for the rest of the scene; the original script does not run in its place.
  • An API function called with arguments of the wrong type raises an error (bad argument #2 to 'set_pos'), and so do an obm.api call with wrong arguments, obm.scripts.hook_api with an unknown interface name, and obm.storage.write with a value larger than 1 MB as JSON. Functions that look something up return nil or false when it is not there (an unknown ref, no player in the menu); they do not raise.
  • A message hook that raises an error does not block the message.

Limits

What Limit
Mods listed 64
Entries scanned per mods folder 256
File in a package 256 MB unpacked
Archive entries Compression ratio at most 1032; Zip64 and encrypted entries are rejected
JSON files (mod.json, contracts, layouts, storage values) 1 MB, nesting depth 64, 1,024 members per object, 131,072 values in all
Settings per mod 12
Bindings per mod 8, each with 2 keys and 1 gamepad button
Debug overlay tabs 16, all mods together
Choices per choice setting 8
Levels per mod 8
Dependencies, conflicts per mod 8 each
Mod id, string setting 63 characters
.glb model 65,535 vertices, 1,048,576 indices, 256 primitives, textures up to 4096 x 4096
obm.api strings 256 different strings per scene, 4,096 bytes each
Event listeners 256, all mods together
Script message hooks 64
Script API hooks 64
Replaced scripts 64
Disabled-script entries 64
Replaced-script coroutines in a scene 128
HUD images 32, each at most 4096 x 4096
Actions 32
obm.ui windows, popups and disabled blocks open at once 32
Ghosts 16, each up to 3,600 frames (6 minutes at the 0.1 s recording rate)
Patrols 32, each up to 12 points
Dynamic lights 16
Enforcer and ally tags 64
Projectiles 32
Props 128
Model replacement prims 256
obm.draw3d shapes per frame 2,048 lines and 4,096 triangles
Instructions per call from the engine 500,000
Lua heap 256 MB
UDP sockets one per mod, 8 in all
UDP payload 1,400 bytes
Contract targets 4

Functions that would go over a limit return false (obm.props.spawn, obm.lights.add_point, obm.actions.register, obm.projectiles.spawn, obm.ghost.play) or raise an error (obm.on, obm.scripts.on_message, hook_api, replace, disable).

API versioning

schema_version in mod.json says which manifest format and API the mod was written for. The current version is 1, and a mod without the field is treated as version 1. A mod with a higher version than the port knows still loads, with a warning on its card, since it may use fields or functions this build does not have.

There is no version number to query from Lua. A mod that wants to run on builds with and without a function can test for it: if obm.ui.same_line then ... end.

Security model

What a mod can do:

  • Read and change the running game through obm, including any of the 716 script interfaces through obm.api. A mod can kill characters, change money on the profile, end missions, and block the mission scripts' messages and calls. Install mods you trust.
  • Read files of active mods (its own and others') through the API functions that take a path.
  • Write files only through obm.storage, into mod_saves/<its id>/, and its settings through obm.config.set. The key becomes a file name, so it is limited to letters, digits, _, - and ., with no ...

What a mod cannot do:

  • Open, list or write other files: io, os, package, debug, dofile and loadfile are missing, load takes only text, and paths given to the API are looked up inside mod packages only.
  • Run bytecode, which could bypass the VM's checks.
  • Change another mod's Lua state, or the string metatable.
  • Pass raw memory addresses to the engine: obm.api only calls interfaces whose parameters are integers, floats and strings, and a ref given to obm.world, obm.ai and the other tables is looked up in the game's object table before it is used.
  • Freeze the game with a Lua loop (the instruction budget; a C library function such as pattern matching is not covered, see Instruction budget) or use unbounded memory (the 256 MB heap).
  • Use the network unless the player allows it.

obm.api is the exception to the checks above: it calls the script interfaces as the compiled mission scripts do, and they trust their arguments. An integer that an interface takes as an object ref is not checked against the object's class, and an index is not checked against the table it indexes, so a wrong call can crash the game or corrupt its state (obm.api.Silevelcontrol__Settargetnum(ref, 100000) writes past the level's target table). Use the obm tables where they cover what you need.

Networking is off by default. Set game.allow_mod_networking to true in the configuration or set OPENBLOOD_ALLOW_NET=1 for a run to enable UDP. Even then, each mod has at most one UDP socket; obm.net.send accepts only numeric IPv4 addresses or localhost, and only loopback (127.0.0.0/8), private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) and link-local (169.254.0.0/16) destinations; packets from other sources, and packets longer than 1,400 bytes, are dropped; there is no DNS. Mods can reach machines on the local network only.

Safe mode (--no-mods or OPENBLOOD_NO_MODS=1) does not scan the mods folders, so a broken mod cannot affect a run started that way. Only the built-in mods shipped with the port run.