Skip to content
Connected RailsConnected Rails

Scenario scripting

A scenario, or an operating day, may name a Lua scenario script. It is not a hook that answers one question. It is the director of the run. It can read the whole world, put trains on the line, give AI drivers timetables and shunt jobs, set the player tasks and tick them off, throw switches, set routes, change the weather, score, move the player to another train, offer the next working, and end the run. Shunting tasks, a dispatcher’s orders, a breakdown halfway, a timed delivery: none of these is a format of its own. Each one is a script against this API.

scenarios/rangierfahrt.ron
(
name: "Rangierfahrt",
consists: [ /* what stands on the line, train 0, 1, … */ ],
player_train: 1,
script: Some("example:rangierfahrt"), // scripts/rangierfahrt.lua
line: Some("example:beispielstrecke"),
)

An operating day takes the same field (days/*.ron → script: Some("<mod>:<name>")). It runs alongside the day’s services and also sees the services.

mods/example/scripts/rangierfahrt.lua is the worked example: the light engine out of the siding, coupling to three machines, bringing them home. It has tasks on the HUD, a speed check while shunting, points, and its own ending.

A script returns a module table. Every handler on it is optional:

local M = {}
function M.on_start() -- once, at the first frame of the run
cr.task("kuppeln", "An den Lokzug kuppeln")
cr.start(story) -- a task that can wait, see below
end
function M.on_tick(dt) -- at every 0.1 s mark of simulation time
end
function M.on_coupled(train) -- world events, see the table below
if train == cr.player() then cr.task_done("kuppeln") end
end
return M

Tasks that wait. A scenario is mostly a story told in order. cr.start(fn) runs fn as a coroutine. It runs up to its first wait as soon as the handler that started it returns, so a wait counts from then. Inside it, these wait without stopping anything else:

call waits for
cr.wait(seconds) simulation time to pass
cr.wait_until(fn [, timeout]) fn() to return true; returns false if timeout seconds ran out first
cr.wait_for(event [, filter [, timeout]]) a world event (optionally one filter(...) accepts); returns its arguments
cr.after(seconds, fn) runs fn once, later
cr.every(seconds, fn) runs fn repeatedly until it returns false
local function story()
cr.message("Lz 77400: an den Lokzug kuppeln.")
cr.wait_until(function() return cr.train(cr.player()).vehicles >= 4 end)
cr.score(10, "Lokzug gekuppelt")
local train = cr.wait_for("stopped", function(t) return t == cr.player() end, 600)
if train == nil then cr.finish(false, "Zu langsam") end
end

World events. Each one arrives as M.on_<event>(...) and as any listener added with cr.on(event, fn) (removed with cr.off(handle)). Train and signal numbers start at 0, as in the RON.

event arguments when
spawned train a train came onto the line: a script’s spawn, a service of the day, a stabled unit put back out, the rear part of an uncoupling
stopped / departed train it came to a stand / started moving
coupled / uncoupled train its consist grew / shrank
entered / left train, road an end of it came onto / left a stabling road or portal (left also when it is withdrawn or coupled away)
movement train, "train" | "shunt" it changed from train movement to shunting movement or back
signal signal, stop a signal changed between stop and proceed
event name a RON event of the scenario fired (every time, for one that is not once)
working_start / working_end service, train a service of the day took / gave up its train
player train the player took over another train (see cr.player())
refused reason the host refused a command of the script’s: a coupling out of reach, a road taken, a train somebody drives
finished success, reason the run ended
call returns
cr.time() / cr.clock() the tick’s mark in simulation time since the start [s] / the same as wall clock [s since local midnight]
cr.date() { year, month, day } of the run
cr.player() the train the player is on duty in; when nobody is (they got out, or a dedicated server, where the players are clients), the scenario’s train. Never nil
cr.scenario_train() the scenario’s own train (player_train, moved by cr.board)
cr.train_count() / cr.trains() number of train slots / indices of every train in service
cr.train(i) { index, number, vehicles, vehicle_names, length, speed_kmh, standing, movement, powered, stabled, empty, edge, s, dir, head, tail, pos, shunt, driver, braked_by_protection }, or nil. edge/s/dir and head are the front end, tail the rear end, pos the leading vehicle’s centre
cr.distance(train, target) metres along the track from its front end to target, positive ahead in the way it runs, or nil beyond 20 km. target is a road name (its mark), another train (its front end), or { edge, s }
cr.at_yard(train, road) whether an end of the train is on that road; a road the line does not have is an error
cr.yards() / cr.yard(name) the line’s roads / { name, kind, edge, s, dir, length, trains }
cr.signal_count() / cr.signal(i) { stop, kind, main, distant, shunt, speed }
cr.switch(node) { position, commanded, moving, locked }
cr.route_count() / cr.route(i) { entry, exit, kind, state }
cr.fired(event) / cr.fired_all() / cr.has_event(event) last firing time of a RON event / all of them / whether the scenario has it
cr.objective(id) "open", "done", "failed" or nil
cr.finished() / cr.bonus() whether the run has ended / the scenario points so far
cr.services() / cr.service(i) / cr.working(train) the operating day’s services { index, number, category, train, departure, arrival, from, to, platform, playable } (train is nil while it is not out) / which service a train is out on
cr.driver(train) "player", "timetable", "shunting", "done" or nil
cr.offset([module]) { edges, nodes, signals, routes, sections, devices }, the offsets of a module on the line being run; without an argument those of the module the run was written for, zeros on its own line
cr.seed() the run’s seed; math.random started from its low 32 bits

Every index a script sees starts at 0: trains, signals, routes, switches, services, as in the RON. Only Lua’s own lists start at 1. cr.trains(), cr.yards() and cr.services() are such lists, so use the values in them (or a service’s index), not their positions.

On a composition. A scenario or a day written for one line also runs on every composition that has that line as one of its modules (see Scenarios). The RON’s indices are moved for it, and so are those of the timetables and shunt jobs a script names by id. Indices a script writes into its own source are not moved: add cr.offset().edges to an edge, as rangierfahrt.lua does for its goal.

Reads see the world as it stood when the call began. A write does not show up in a read until the next tick.

Writes are commands. They take effect when the handler returns, in the order they were given. Two kinds of “no” come back:

  • A wrong argument is an error at the call: a road the line does not have, a switch that is not one, a train that does not exist, an unknown timetable or job. Like any Lua error it switches the script off.
  • A refusal by the world comes back as a refused event at the next tick, with the reason: a coupling with nothing in reach, a road already taken, a train somebody is driving. Nothing of it was done, and the script runs on.
call does
cr.message(text) / cr.announce(text) a message to the player / an announcement
cr.task(id, text) / cr.task_done(id) / cr.task_failed(id) / cr.remove_task(id) the HUD’s task list
cr.score(points, reason) / cr.finish(success, reason) points / the end of the run
cr.fire(event) fires a RON event of the scenario, actions and all
cr.set_switch(node, "straight" | "diverging") throws a switch
cr.request_route(i) / cr.release_route(i) sets or releases a route of the interlocking
cr.set_weather("Rain") / cr.set_rail("Slippery") weather preset / rail condition, spelled as in the RON
cr.spawn(consist) builds a train and returns its index at once; every write takes it in the same call (cr.shunt, cr.set_number, …)
cr.drive(train, timetable) gives it an AI driver for a timetable: "<mod>:<name>" or a table
cr.shunt(train, job) gives it an AI driver for a shunt job: "<mod>:<name>" (jobs/*.ron) or a table
cr.secure(train) takes its driver off and leaves it braked (refused for a train a player drives, as are cr.drive and cr.shunt)
cr.couple(train [, other]) / cr.uncouple(train, n) couples to what it stands against (or to other) / parts behind vehicle n
cr.place(train, road) / cr.withdraw(train, portal) puts it on a road / takes it off the line at a portal
cr.set_number(train, number) renumbers it
cr.board(train) makes it the scenario’s train and the one scored: whoever was driving the old one sits down at its desk
cr.offer_working(service) offers a service of the day as the player’s next working
cr.log(text) a line in the log

A consist is the same value as a consists: entry, written as a table. A road is a string and a point is { edge, s, dir }:

local pilot = cr.spawn{
number = "Lz 77402",
vehicles = { "example:br101_afb" }, -- or { vehicle = "…", count = 3, variant = 1 }
at = "Portal Ost", -- or { edge = 1, s = 300, dir = -1 }
}
-- On the example line: in from the east portal, up to the machines standing at km 3.8.
cr.shunt(pilot, { name = "Vorziehen", moves = {
cr.moves.draw_up({ edge = 0, s = 3800 }), -- head onto this point (`set_back`: the rear)
cr.moves.couple(), -- to whatever stands against it
cr.moves.uncouple(0), -- behind vehicle 0, the front one
cr.moves.stand(),
} })

A move ends where the buffers are met, whatever the mark said. set_back measures the rear of the train, the end that leads a reversing move. A road as a target is its mark. The points have to lie right: a script throws them (cr.set_switch) or sets a route.

A shunt job as a file is jobs/<name>.ron (ShuntJob, see modding guide). mods/example/jobs/lokzug_abstellen.ron is one.

Texts a script writes are mod content, in the language the mod ships, like a scenario’s RON messages. The simulator’s own words around them (the task heading, the next-working line) are translated.

The script runs in a fresh Lua 5.4 state of its own for every run, with table, string, math and coroutine. There is no io, no os, no require, no filesystem and no network. It never holds a handle on the simulation. Everything goes through cr, and the host checks every command before it applies it.

  • No way out. load takes source text only, never precompiled bytecode. loadfile, dofile, string.dump, collectgarbage and print are gone. The state may hold 64 MB.
  • Same every time. pairs and next visit keys in order: booleans, then numbers, then strings, each ascending. Tables as keys have no order to give and are ordered by address. math.random is a seeded xorshift. The seed comes from the script’s name and the start of the run, so the same scenario on the same day draws the same numbers.
  • Paced by the simulation clock. The script runs at the first frame at or past each 0.1 s mark, and cr.time() reads the mark, so a cr.wait ends on the same mark at 30 or at 144 frames a second. What the world looks like at that moment is the frame’s.
  • A runaway script is stopped. One call may spend 200 000 units, where a function call is one unit and so is every thousand instructions, and a quarter of a second. Catching the error with pcall buys nothing: once out, every further step raises again. Past the limit, or after any error, the script is switched off and none of that call’s commands are applied. The log says where it failed, and the HUD says that it stopped. The run goes on without it.
  • Keep state in locals. The state is fresh for every run, so a script does not need to reset anything.

The scenario belongs to the server. The script runs in single player and on the dedicated server, and never on a client. What the world made of its commands goes to the clients, and only that: a refused command goes nowhere. A shunting command goes as its result, so a coupling arrives with the two ends it joined and an uncoupling with the slot of its rear part. A client repeats these without checking reach against its own positions, which may not be in sync yet. Every command carries its place in the server’s log. A client that joins late is first sent the whole log, and one that reconnects is sent it again; a client skips what it has already applied, so nothing happens twice. The script never runs twice, and peers never take different branches because one of them sees a train a few centimetres further on.

What this costs a script author: nothing, as long as the world is changed through cr. The AI drivers a script hands out are the server’s like every other driver. On a client only the train is built.

The index cr.spawn returns is the same on every peer, whenever a peer hears about the spawn. Once the world is built, each source of new trains (the operating day, the script, uncoupling) fills a sequence of train indices of its own, interleaved with the others. So the k-th train a script builds always lands in the same slot, whatever the operating day has put on the line in the meantime. The slots no source has filled yet stand as empty stabled consists, which cr.trains() leaves out.

Before the director, a scenario script was on_load(ctx) / on_frame(ctx) answering with a table (message, fire, switch). Such a script still runs: the director builds the old ctx out of cr and turns the answer into commands. An unknown event name or a bad switch command is logged and skipped, as before. on_frame now runs at the 0.1 s marks rather than every frame, with dt the time between them. scripts/probefahrt.lua is one. A line script keeps that shape. It is a behaviour hook of the line (see modding guide), not a scenario.