Whilst i do see value in this myself, i doubt i'll be able to convince someone at wube of its usefulness, just posting this here because i got "challenged" to

The idea is near the bottom, with 2 current/alternative ways of doing it posted between here and there:
Difficulty level 1: Scheduling something via script.on_tick
This works and accomplishes the task, however the lua handler runs every tick, not very practical if you only have something to schedule occasionally.
Code: Select all
global.task_for_tick = {}
...
global.task_for_tick[tick] = 'some task'
...
script.on_tick(function (event)
if global.task_for_tick[tick] then
-- do the task
global.task_for_tick[tick] = nil
end
end)
Register the handler to only run for the ticks you want tasks to run in, comes with a little managerial overhead, as well as requiring proper on_load handling.
Code: Select all
global.task_for_tick = {}
...
global.task_for_tick[tick] = 'some task'
script.on_nth_tick(tick, handler)
...
function handler(event)
if global.task_for_tick[tick] then
-- do the task
global.task_for_tick[tick] = nil
script.on_nth_tick(tick, nil)
end
end
...
script.on_load(function (event)
for tick, _ in pairs(global.task_for_tick) do
script.on_nth_tick(tick, handler)
end
end)
The script interface i am proposing:
- you will not need to un-register in the handler to prevent it from running on a future modulus tick, since it unregisters itself automatically
- scheduling on the same tick as an on_nth_tick will not cause that handler to reset
- trying to register a handler for the current or a previous tick should fail, should also quickly expose any flaws in the on_load handler
- might be a little too advanced for most, since unlike using on_nth_tick as a cronjob requires management of global & knowledge of on_load
- uses == instead of % to determine on the c++ side whether or not to trigger the lua handler (instead of e.g. doing it from within lua's on_tick)
I do understand that it is possible to emulate the above using on_nth_tick just fine, this would just be a "cleaner shortcut" for scheduling, which in theory should be better for performance in marginally small amounts (no task checks every tick in lua, and not running a modulus for each scheduled on_nth_tick)
Code: Select all
global.task_for_tick = {}
...
global.task_for_tick[tick] = 'some task'
script.once_at_tick(tick, handler)
...
function handler(event)
if global.task_for_tick[tick] then
-- do the task
global.task_for_tick[tick] = nil
end
end
...
script.on_load(function (event)
for tick, _ in pairs(global.task_for_tick) do
script.once_at_tick(tick, handler)
end
end)