The Context table (cxt)

Name

cxt – table of useful information regarding the current action

Synopsis

cxt = {
    actor = <Creature>,
    actor_pos = <position>,
    victim = <Creature>,
    victim_pos = <position>,
    item_type = <ItemType>,
    item_pos = <position>,
    tile = <Tile>,
    tile_pos = <position>,
    pos = <position>,
    originator = <Player>
}

Description

cxt is a global Lua variable, which is set by the game whenever Lua code is executed in response to any in-game action.

Examples of situations where this would apply include item or tile "callback" functions, such as on_walk_over, on_pick_up, on_drop, etc., as well as "hook" functions (HOOK_WEAPON_DOWNSWING, HOOK_WEAPON_PARRY, and so on). Basically, during the execution of any of those (or similar) functions, you can rely on the cxt table being present and correctly set up for whatever action is currently taking place.

The cxt table contains information associated with the current action. For example:

Note that not all fields will be applicable for all actions. If any field is "not applicable" then it will be set to nil.

Bugs

The use of a global variable for this purpose, as opposed to (say) just passing some extra parameter(s) to the relevant Lua functions, could probably be considered a bug, at least by software development purists. However, it is probably too late to change this now.

Examples

Many actions will want to play a sound when they happen. For example, to make bats "screech" when they are hit, the following code is added to the on_damage function of the vampire bat MonsterType:

kts.PlaySound(cxt.pos, s_screech, 15000)

(Note the use of cxt.pos to find the correct position to play the sound at.)

The following code finds out how many gems the actor is holding. This might be used to implement a door that can only be opened when you are holding a certain number of gems, for example:

local num_held = kts.GetNumHeld(cxt.actor, i_gem)

The following determines whether the tile associated with the action is a crystal ball tile. This might be used in the melee_action of a wand, to detect whether the wand is being used to hit a crystal ball:

if cxt.tile == t_crystal_ball then ...

The following code calculates a position 2 squares east, and 3 squares south of the tile associated with an action (but also taking into account dungeon rotation). This might be used in a pressure plate Tile's on_walk_over action, to trigger some effect on a nearby tile:

local pos = kts.RotateAddPos(cxt.tile_pos, 2, 3)

Many more examples can be found by looking in the Knights Lua files or in existing Knights mods.