Inter-script Communication

Inter-script communication (ISC) allows scripts to communicate with each other, mainly by calling functions in the scripts themselves. It can also be used as a more powerful and intuitive alternative to the registry.

knCall(script: enum | lightuserdata, function: string, [...]): [...]

Call a function in another script, returning its result. The script should either be one of KN_MENU, KN_MOVIE, KN_HUD, or a pointer to a script’s lua_State as a light userdata. The function should be a string naming the function to call. The arguments that will be passed to the function should follow.

If there is an error, it will be raised as a Lua error. This includes an invalid script being specified, the scene containing the target script not being loaded, the function not being found, and the called function itself raising its own error.

There are some notable caveats to the current implementation:

  • Integers will be cast to floats due to Lua not exposing any way of telling the difference between an integer and a number.

  • Values of the types function, userdata, and thread cannot be copied between scripts and will be replaced by ``nil``.

knOwnHandle(): lightuserdata

Returns a pointer to the script’s lua_State pointer as a light userdata. This is useful for informing “master” scripts like the menu or HUD of room and obstacle scripts via knCall(), so that they themselves can use knCall to call directly into your script.

Examples

Using knCall()

In hud/main.lua:

1function addPoints(pts)
2    points = points + pts
3    return points
4end

In obstacles/customtop.lua:

1function tick()
2    if not mgIsCleared() then
3        if mgBodyIsBroken(body) then
4            local points = knCall(KN_HUD, "addPoints", 3)
5        end
6    end
7end

Using knOwnHandle()

 1-- Assume that informCreated(script) and informDestroyed(script) tell the HUD
 2-- script that these obstacle/room scripts have been created and destroyed,
 3-- respectively.
 4
 5-- In obstacle/myobstacle.lua
 6function init()
 7    knCall(KN_HUD, "informCreated", knOwnHandle())
 8end
 9
10function shutdown()
11    knCall(KN_HUD, "informDestroyed", knOwnHandle())
12end
13
14function isCleared()
15    return mgIsCleared()
16end
17
18-- In hud/main.lua
19function draw()
20    -- ... maybe in a loop ...
21    if knCall(obstacle, "isCleared") then
22        -- ... do something interesting! ...
23    end
24end