kts.AddTask

Name

kts.AddTask – run a Lua function in the background

Synopsis

kts.AddTask(task)

Description

This function calls the Lua function task as a coroutine.

The task function may call coroutine.yield at any time, passing a number of milliseconds as an argument; this will cause the coroutine to sleep for that number of milliseconds, before it is resumed (by the game).

If the task function returns, then the background task terminates and it is not called again. (Any return values are ignored.)

kts.AddTask might be useful for setting up special scenarios where certain effects occur at regular intervals, or upon certain triggers. For example, in the Tutorial, the "Chamber of Bats" room (when it is active) spawns vampire bats at particular intervals; this is handled by a background task.

Return Value

No value is returned.

Errors

An error would result if the passed value is not a function.

Notes

The coroutine function should not "block" for an extended period of time, as this would cause the game to freeze up. Instead, the coroutine should generally just do a minimal amount of work (e.g. spawning new monsters, adjusting dungeon tiles etc), before sleeping for a number of milliseconds (by calling coroutine.yield). This will allow the game to run for a period of time before the coroutine resumes once again.

Note also that all "callback" functions (on_walk_over, on_pick_up, on_activate etc.) are actually implemented as coroutines, which means that they are able to call coroutine.yield if desired.

Examples

An example of using kts.AddTask can be found in knights_data/server/tutorial/init.lua (search for "AddTask" or "function bat_task"). Briefly, this works by calling kts.AddTask(bat_task) at the start of the tutorial. The "bat task" is then constantly running in the background. The code for function bat_task looks like the following:

function bat_task()
    if bat_task_active then
        -- Do some stuff, e.g. call kts.AddMonster to add new vampire bats.
    end

    -- Sleep for 250 milliseconds.
    coroutine.yield(250)

    -- The bat task is meant to run forever, so here we just call bat_task() again.
    -- (This is a tail call, so it does not grow the stack endlessly.)
    -- (Note that an alternative way of coding this would have been to use a "while" loop.)
    return bat_task()
end

See Also

Chapter on Coroutines in the "Programming in Lua" book.