Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ Template for new versions:
## API

## Lua
- ``dfhack.timeout_until``: new function to schedule a callback to run on a specified in-game tick

## Removed

Expand Down
9 changes: 9 additions & 0 deletions docs/dev/Lua API.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3824,6 +3824,15 @@ Core context specific functions:
Returns the timer id, or *nil* if unsuccessful due to
world being unloaded.

* ``dfhack.timeout_until(tick,callback)``

Arranges for the callback to be called once the in-game
tick count (``df.global.world.frame_counter``) reaches
the specified value. The timer is canceled when the
world is unloaded, and cannot be queued until it is
loaded again. Returns the timer id, or *nil* if
unsuccessful due to world being unloaded.

* ``dfhack.timeout_active(id[,new_callback])``

Returns the active callback with the given id, or *nil*
Expand Down
34 changes: 34 additions & 0 deletions library/LuaTools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2036,6 +2036,38 @@ int dfhack_timeout(lua_State *L)
return 1;
}

int dfhack_timeout_until(lua_State *L)
{
using df::global::world;

// Parse arguments
lua_Number tick = luaL_checknumber(L, 1);
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_settop(L, 2);

if (!Core::getInstance().isWorldLoaded())
{
lua_pushnil(L);
return 1;
}

int delta = tick - world->frame_counter;

if (delta <= 0)
luaL_error(L, "Invalid timeout: %d", delta);

// Queue the timeout
int id = next_timeout_id++;
tick_timers.insert(std::pair<int,int>(tick, id));

lua_rawgetp(L, LUA_REGISTRYINDEX, &DFHACK_TIMEOUTS_TOKEN);
lua_swap(L);
lua_rawseti(L, -2, id);

lua_pushinteger(L, id);
return 1;
}

int dfhack_timeout_active(lua_State *L)
{
int id = luaL_optint(L, 1, -1);
Expand Down Expand Up @@ -2147,6 +2179,8 @@ static void Lua::Core::InitCoreContext(color_ostream &out)

lua_pushcfunction(State, dfhack_timeout);
lua_setfield(State, -2, "timeout");
lua_pushcfunction(State, dfhack_timeout_until);
lua_setfield(State, -2, "timeout_until");
lua_pushcfunction(State, dfhack_timeout_active);
lua_setfield(State, -2, "timeout_active");

Expand Down
Loading