Skip to content

callbacks

Callbacks are functions you write and hand to the game, which calls them when something happens: a hit lands, a round begins, a button is pressed. Combat callbacks go in perks, enchantments, rules and fighter behaviours. The others belong to a particular feature, such as an interface view, a story sequence or an opponent tactic. Each section says when it runs and what it may return.

Runs once when the first round begins.

Signature: on_fight_begin = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: First round start, before that round’s on_round_begin.

on_fight_begin = function(parameters, fighter, event)
fighter:add_magic_charge(0.35)
end,

Does not run when the map opens or a profile loads.

Runs at the start of every round, to reset or recharge things.

Signature: on_round_begin = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Each round begins; in round one it follows on_fight_begin.

on_round_begin = function(parameters, fighter, event)
sf2.log.info("Round " .. tostring(event.round))
end,

Behavior state with round lifetime starts fresh each round.

Runs every active combat frame, for timers and cooldowns.

Signature: on_tick = function(parameters, fighter, event); stateful behaviors receive self instead of parameters.

Returns: Nothing.

When: Once per active combat frame (60 per second of combat time), before movement and collisions. Paused combat, round transitions and finished fights do not tick.

-- elapsed is an integer state field with round lifetime.
on_tick = function(self, fighter, event)
self.state.elapsed = self.state.elapsed + event.delta_frames
if self.state.elapsed >= 120 then
self.state.elapsed = 0
sf2.log.info("Two seconds of combat elapsed")
end
end

event.frame counts active frames cumulatively across rounds; seconds is frame / 60; delta_frames is 1 and delta_seconds is 1/60 (pause time excluded). Actors tick once they have appeared; main fighters after the round-begin callbacks. Keep the handler small, and avoid work that fails or logs every frame. You cannot modify a pending hit from a tick. See combat scripting.

Runs when any fighter or actor starts an animation, such as a spell cast.

Signature: on_animation_start = function(parameters, fighter, event); stateful behaviors receive self instead of parameters.

Returns: Nothing.

When: During active rounds. Not delivered during round transitions, after a fight ends, or in Local Versus.

on_animation_start = function(parameters, fighter, event)
if event.target == "self"
and event.animation_name == sf2.mod.id .. ":moves/cast" then
sf2.log.info("Cast started")
end
end,

Both sides receive every event. animation_name is the exact name (your moves use their full move ID); target is "self", "opponent" or "other" (another actor, including projectiles) relative to the receiving fighter; frame is the combat frame. other does not say who owns a projectile, so filter on the move name, or look projectiles up with fighter:projectiles. The event is a copy: if it was delayed behind another Lua callback, a fighter:snapshot taken now may show a later animation. See combat scripting.

Runs when an animation ends; pairs with on_animation_start.

Signature: on_animation_end = function(parameters, fighter, event); stateful behaviors receive self instead of parameters.

Returns: Nothing.

When: Same ordering and filtering as on_animation_start.

on_animation_end = function(parameters, fighter, event)
if event.animation_name == sf2.mod.id .. ":moves/cast" then
sf2.log.info("Cast finished")
end
end,

The event has the same animation_name, target and frame as the start callback. An interrupted or replaced animation does not always produce an end event.

Runs when one of your actors has finished appearing, to set up its state.

Signature: on_actor_spawn(parameters, fighter, event) or on_actor_spawn(self, fighter, event) for stateful behaviors.

Returns: Nothing.

When: Once per actor, after its entry animation and placement. Not called for failed spawns, perks, rules or enchantments.

on_actor_spawn = function(self, fighter)
self.state.id = fighter.actor_id
end,

fighter.actor_id, actor_definition, actor_owner and side identify the actor; fighter.actor works only during the callback. State is private to the actor and not saved. See combat scripting.

Runs when one of your actors leaves the fight, for cleanup.

Signature: on_actor_end(parameters, fighter, event) or on_actor_end(self, fighter, event) for stateful behaviors.

Returns: Nothing.

When: Once, just before the actor is removed.

on_actor_end = function(_, fighter)
sf2.log.info(fighter.actor_id .. " ended: " .. fighter.actor_end_reason)
end,

fighter.actor_end_reason is "removed", "died", "expired", "owner_changed" or "round_ended" (a surrender also counts as "round_ended"). The actor’s ID, final health and state can be read, but you cannot command it. See combat scripting.

Runs on the defender just before a hit is applied, to reduce incoming damage.

Signature: on_damage_resolving = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: The final incoming hit is about to reduce health.

on_damage_resolving = function(parameters, fighter, event)
if event.damage > 0 then
fighter:scale_incoming_damage(0.5)
end
end,

event.damage is the incoming damage not yet applied; blocked and critical are also set. This is the only callback where fighter:scale_incoming_damage is available.

Runs on the attacker just before a hit’s damage is applied, so you can scale or add to it.

Signature: on_damage_dealing = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: After damage, block and critical are worked out, before the defender’s shields and health loss. Zero-damage hits still call it.

on_damage_dealing = function(parameters, fighter, event)
if event.critical and not event.blocked then
fighter:scale_outgoing_damage(1.5)
end
end

event.damage, blocked and critical are copies of the pending hit. fighter:scale_outgoing_damage and fighter:add_outgoing_damage change it, so several handlers combine in order while your event keeps the starting values. The defender’s rules still apply afterwards. To unblock a hit use on_hit_pre_crit. Unlike on_damage_dealt, health has not been lost yet.

Runs after the block decision but before the critical roll; the only place to change whether a hit is blocked.

Signature: on_hit_pre_crit = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Every hit, on both sides, before on_hit_post_crit.

-- While the "unblockable" flag lasts, this fighter's hits cannot be blocked.
on_hit_pre_crit = function(self, fighter, event)
if event.target == "opponent" and event.blocked and fighter:has_flag("unblockable") then
fighter:set_hit_blocked(false)
end
end

event.blocked is the current decision; target and the attack-kind flags are as in on_hit_post_crit, but there is no damage or critical yet. Change the decision with fighter:set_hit_blocked. Perk <HitPreCrit> triggers run first, so you see their changes.

Runs once block and critical are decided; read what kind of hit it was.

Signature: on_hit_post_crit = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Every hit, on both sides, after block and critical are decided.

on_hit_post_crit = function(self, fighter, event)
if event.target == "opponent" and (event.ranged or event.magic) then
self.state.armed = false
end
end

event.target is "self" when this fighter is hit and "opponent" when it is the attacker. weapon, unarmed, ranged and magic give the attack kind; damage, blocked and critical are also set. The hit cannot be changed here; use on_post_hit or on_damage_dealing.

Runs after on_hit_post_crit; the attacking side can add to or scale the hit’s damage.

Signature: on_post_hit = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Every hit, with the same event fields as on_hit_post_crit.

on_post_hit = function(self, fighter, event)
if event.target == "opponent" and not event.blocked then
fighter:add_outgoing_damage(self.params.bonus)
end
end

Only when event.target == "opponent" (this fighter attacks) can you use scale_outgoing_damage and add_outgoing_damage. To reduce a hit you receive, use on_damage_resolving.

Runs on the defender after it has lost health.

Signature: on_damage_received = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Health was reduced by a positive amount.

on_damage_received = function(parameters, fighter, event)
sf2.log.debug("Damage received: " .. tostring(event.damage))
end,

The event has the victim’s health before and after, and the hit flags. Healing here cannot undo a lethal hit. To reduce the damage instead, use on_damage_resolving.

Runs on the attacker after its hit has taken health from the opponent.

Signature: on_damage_dealt = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: A positive health loss is credited to this attacker.

on_damage_dealt = function(parameters, fighter, event)
sf2.log.debug("Damage dealt: " .. tostring(event.damage))
end,

The health fields describe the fighter who was hit. Projectile damage is credited to its owning main fighter, and the callback does not say which projectile hit. See combat scripting.

Runs on the defender when it blocks a hit.

Signature: on_block = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: A blocked hit resolves, even at zero damage.

on_block = function(parameters, fighter, event)
sf2.log.debug("Blocked a hit")
end,

Runs on the defender; the health and damage fields describe that defender. See combat scripting.

Runs on the attacker when its hit is a critical hit.

Signature: on_critical = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: A critical hit resolves.

on_critical = function(parameters, fighter, event)
sf2.log.debug("Landed a critical hit")
end,

Runs on the attacker; the health and damage fields describe the victim.

Runs when the player picks a direction on a combat button.

Signature: on_control_direction = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: During a round, on the player only, after fighter:set_control_directions was used.

on_control_direction = function(self, fighter, event)
if event.direction == "up" then
self.state.stance = 1
end
end

event.control is the button (currently "raid_charge") and event.direction is the direction the player chose: "up", "right", "down" or "left". It runs at the next simulation step after the choice, the same as other combat callbacks, and is dropped if the round has ended by then.

Runs when the fighter’s combo counter changes.

Signature: on_combo_changed = function(parameters, fighter, event); stateful behaviors receive self instead of parameters.

Returns: Nothing.

When: After the combo count updates; event.combo is the new count, event.last_combo the previous one.

on_combo_changed = function(self, fighter, event)
self.state.combo = event.combo
end

When a combo times out, combo is zero and last_combo is the finished count. Counts below the game’s display threshold do not call it and not every reset produces an event, so use round or fight state lifetimes to reset your own data. Scripts cannot change the counter.

Runs when the fighter moves up or down a style rank.

Signature: on_style_changed = function(parameters, fighter, event); stateful behaviors receive self instead of parameters.

Returns: Nothing.

When: After a new style rank is reached; progress within the same rank does not call it.

on_style_changed = function(self, fighter, event)
self.state.style = event.style_rank
end

The event has style_rank (from zero), style_name, style_gain (progress within the rank) and is_hit (whether a hit caused it). Do not use the localized style_name as a stable ID. The meter cannot be changed from here.

Runs when a round finishes, for per-round cleanup.

Signature: on_round_end = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Once per round, when the end-of-round pose completes or the player surrenders.

on_round_end = function(parameters, fighter, event)
sf2.log.info("Round finished")
end,

event.won does not exist here; the result fields belong to on_fight_end.

Runs once when the whole fight finishes.

Signature: on_fight_end = function(parameters, fighter, event); with state, function(self, fighter, event).

Returns: Nothing.

When: Before the results screen, including a surrender.

on_fight_end = function(parameters, fighter, event)
if event.won then
sf2.log.info("This fighter won")
end
end,

event.player_result is "win", "loss", "surrender" or "timeout". event.won is relative to the callback’s fighter, so use it to count that fighter’s victories.

Runs when the player presses Back or Escape on your menu, replacing the default close.

Signature: on_back = function(view) ... end

Returns: Nothing.

When: Back or Escape on the foreground menu or modal. HUD views never receive it.

sf2.ui.open {
id = "notice", mount = "modal",
root = { id = "ok", kind = "button", width = 240, height = 60, text = "OK" },
on_click = function(view) sf2.ui.close(view) end,
on_back = function(view) sf2.ui.close(view) end,
}

Because this replaces the default close, close the view yourself (or leave it open). Omitting on_back closes with reason back; closing inside the callback gives reason script. Use on_close for releasing references.

The handler passed to sf2.story.before_fight; decides whether the fight starts.

Signature: on_before_fight(request) -> boolean|nil

Returns: true continues, false cancels, nil holds the fight until you call sf2.story.resume_fight. An error cancels the entry and removes the handler.

When: When your registered fight is about to start from the progression map.

sf2.story.before_fight(first_fight, function(request)
sf2.log.info("Entering " .. request.fight)
return true
end)

request.fight is the qualified fight ID; the rest of the request is opaque. Do not call resume_fight from inside this callback; return true instead. A later callback, such as a button click, may resume a held fight. See Story battles.

Runs when a story sequence stops before its last step finishes.

Signature: on_cancel() -> nil

Returns: Nothing.

When: Once, when a sf2.story.play_sequence stops early: a scene change, a refused step, or on_step returning false.

sf2.story.play_sequence {
steps = steps,
on_cancel = function() sf2.log.info("Will show the message again next visit") end,
}

Not called on script shutdown or profile change, and never after on_complete.

Handles a value change on a view’s toggle, slider or text input.

Signature: on_change = function(view, widget_id, value) ... end

Returns: Nothing.

When: The player changes a visible, enabled widget in the foreground view.

sf2.ui.open {
id = "options", mount = "menu",
root = { id = "root", kind = "column", width = 400, height = 100,
children = {
{ id = "challenge", kind = "toggle", width = 400, height = 48, text = "Challenge rules" },
},
},
on_change = function(_, widget_id, value)
if widget_id == "challenge" then challenge = value end
end,
}

value is a boolean for toggles, a number from 0 to 1 for sliders, and a string for text inputs. A widget’s own on_change is function(view, value) and skips this handler. sf2.ui.update and repeated identical values do not notify. See Menus and settings.

Handles clicks on buttons that have no on_click of their own.

Signature: on_click = function(view, widget_id) ... end

Returns: Nothing.

When: An enabled, visible button in the foreground view is activated.

sf2.ui.open {
id = "choice", mount = "menu",
root = { id = "cancel", kind = "button", width = 240, height = 48, text = "Back" },
on_click = function(view, widget_id)
if widget_id == "cancel" then sf2.ui.close(view) end
end,
}

widget_id is the declared ID, not the label. A button’s own handler is function(view) and skips this one. An error closes the view. This callback cannot launch fights; pass choices to gameplay through Lua state. See Menus and settings.

Runs when a view closes, to clear pending choices or Lua references.

Signature: on_close = function(view, reason) ... end

Returns: Nothing.

When: Once after a successfully mounted view closes.

local chooser
chooser = sf2.ui.open {
id = "choice", mount = "menu",
root = { id = "cancel", kind = "button", width = 240, height = 48, text = "Back" },
on_click = function(view) sf2.ui.close(view) end,
on_close = function(view, reason)
if chooser == view then chooser = nil end
sf2.log.debug("Chooser closed: " .. reason)
end,
}

reason is script (Lua or the game closed it), back, scene (scene torn down), error (a click or update failed) or destroyed. Inside the callback sf2.ui.is_open(view) is false, sf2.ui.update fails, and opening another view is rejected, so open follow-ups later. It does not run for failed mounts or script shutdown, so never use it to grant rewards or save results. See Menus and settings.

Runs once after the last step of a story sequence finishes.

Signature: on_complete() -> nil

Returns: Nothing.

When: After the last step of a sf2.story.play_sequence is acknowledged or finishes. Never after cancellation.

sf2.story.play_sequence {
steps = { { act_screen = { lines = { { text = ending, frames = 180 } } } } },
on_complete = function() sf2.log.info("Safe to continue the story") end,
}

A dialog’s final step counts as acknowledged on its last button, or on Back unless ignore_back is set.

Chooses what a scripted opponent does next.

Signature: on_decide = function(memory, event) ... end

Returns: An action from event.actions (return the candidate table itself), "wait" for no new action until the next decision, or nil to let the native tactic decide.

When: The native AI reaches an eligible move decision, at most once per six frames.

sf2.ai.register {
id = "patient", template = "Standard",
on_decide = function(memory, event)
memory.next_attack = memory.next_attack or 0
if event.seconds < memory.next_attack then return "wait" end
local best
for _, action in ipairs(event.actions) do
if action.type == "attack" and (not best or action.priority > best.priority) then
best = action
end
end
if best then memory.next_attack = event.seconds + 1 end
return best
end,
}

Use it with type = "tabular" (the default) and a template such as "Standard" for fallback behavior.

event.self and event.opponent are fighter snapshots (the opponent may be nil; snapshots include animation). event.actions is the list of currently legal actions, possibly empty, already filtered by moves, conditions and equipment. Each has name, type, priority (move priority, not an AI score), timing (nominal clip length, not a guaranteed hit window) and inputs; Forward and Back inputs are relative to facing. Returning a candidate selects the original action even if you edited the copy. To react to the opponent, check event.opponent.animation.intervals for an "attack" interval rather than guessing from move names.

memory is private to this fighter and tactic, and survives between decisions but not save/reload. Script-level variables are shared by every fighter using the tactic, so keep per-fighter data in memory. An error, an invalid or stale action, or running over 200,000 instructions disables the callback for that fighter and the native AI takes over. See Scripted AI.

Right after a wall bounce, with the player within reach, the game may start a wall escape (usually a wall jump) on its own, without calling on_decide that time, so an opponent cannot be combo’d against the wall forever.

Builds the encounter plan for a mode fight just before it starts, or opens a screen to choose one.

Signature: on_prepare = function(request, event) ... end

Returns: An encounter plan, or nil to leave the request pending. {} accepts the fight unchanged.

When: The player enters a mode whose current encounter has no saved plan, before entry is charged.

sf2.modes.register {
id = "expedition", fights = { first, second, third }, repeatable = true,
on_prepare = function(_, event)
return {
opponents = { rivals[sf2.random.integer("encounter_rng", 1, #rivals)] },
level = event.step + 2,
rounds = 1, round_time = 60,
}
end,
}

This assumes registered fight handles, a rivals list of fighter handles and a declared integer state field encounter_rng. event has one-based step, total, completions before this attempt, and the blueprint’s fight_id.

A plan can only name content that already exists, so register fighters and rules at load time and use their handles. All fields are optional and inherit from the blueprint; level applies to opponents only, and an empty rules array removes all blueprint rules. Location, music and rewards always come from the blueprint.

To let the player choose, return nil, open a UI, and call sf2.modes.resolve(request, { player = hero }) then sf2.ui.close(view) from its callback. The chosen player is used for this encounter only; saved equipment is unchanged (see the character guide).

The plan is saved with the mode step, so a reload or a retry after a failed launch reuses it without calling on_prepare or drawing random numbers again. Pending screens are not saved: leaving the scene or changing profile cancels preparation. Random draws and state writes before a failure are not rolled back, so draw only after the player commits. See Underworld and modes.

Runs when a mode fight ends and chooses the next fight or ends the mode.

Signature: on_result = function(result) ... end

Returns: A fight handle from this mode’s fights (play it next), "complete" (finish the run, even after a loss), or nil for normal win/loss progression.

When: Once per settled mode fight, after outcome and rewards. Synchronous; it cannot wait for a UI choice.

sf2.modes.register {
id = "branching_trial", fights = { first, middle, final }, repeatable = true,
on_result = function(result)
if not result.won then return first end
if result.step == 3 then return "complete" end
return nil
end,
}

result is a copy with won, step (one-based roster position), total (roster size, not a route length), completions before this result, and fight_id. A failure or invalid return logs a warning and uses default progression. Local Lua variables are not saved; use the state API for anything that must persist, and decide before writing state since side effects are not rolled back. Modes with this callback hide the linear completion bricks. Use on_prepare for generated encounters. See Underworld and modes.