z_mirror/flib
git clone https://git.raiguard.me/z_mirror/flib
a9f2be7
trunk
1--- Schedule tasks to be executed later. 2--- ```lua 3--- local flib_on_tick_n = require("__flib__.on-tick-n") 4--- ``` 5--- @class flib_on_tick_n 6local on_tick_n ={} 7 8--- Initialize the module's script data table. 9--- 10--- Must be called at the **beginning** of `on_init`. Can also be used to delete all current tasks. 11function on_tick_n . init () 12if not storage . __flib then 13storage . __flib ={} 14end 15--- @type table<number, flib.OnTickNTasks> 16storage . __flib . on_tick_n ={} 17end 18 19--- Retrieve the tasks for the given tick, if any. 20--- 21--- Must be called **during** `on_tick`. 22--- @param tick number 23--- @return flib.OnTickNTasks? 24function on_tick_n . retrieve ( tick ) 25-- Failsafe for rare cases where on_tick can fire before on_init 26if not storage . __flib or not storage . __flib . on_tick_n then 27return 28end 29local actions =storage . __flib . on_tick_n [ tick ] 30if actions then 31storage . __flib . on_tick_n [ tick ] =nil 32return actions 33end 34end 35 36--- Add a task to execute on the given tick. 37--- @param tick number 38--- @param task any The data representing this task. This can be anything except for a `function`. 39--- @return flib.OnTickNTaskID ident An identifier for the task. Save this if you might remove the task before execution. 40function on_tick_n . add ( tick , task ) 41local list =storage . __flib . on_tick_n 42local tick_list =list [ tick ] 43if tick_list then 44local index =# tick_list + 1 45tick_list [ index ] =task 46return { index =index , tick =tick } 47else 48list [ tick ] ={ task } 49return { index =1 , tick =tick } 50end 51end 52 53--- Remove a scheduled task. 54--- @param ident flib.OnTickNTaskID The identifier object for the task, as returned from `on-tick-n.add`. 55function on_tick_n . remove ( ident ) 56local tick_list =storage . __flib . on_tick_n [ ident . tick ] 57if not tick_list or not tick_list [ ident . index ] then 58return false 59end 60 61tick_list [ ident . index ] =nil 62 63return true 64end 65 66--- A unique identifier for a previously added task, used in `on-tick-n.remove`. 67--- @class flib.OnTickNTaskID 68--- @field tick number The tick this task is scheduled for. 69--- @field index number The tasks' index in the tick's `Tasks` table. 70 71--- A table of tasks. 72--- 73--- Each task can be anything that is not a function, as specified in `on-tick-n.add`. 74--- 75--- **This is not an array, there may be gaps. Always use `pairs` to iterate this table.** 76--- 77--- # Example 78--- 79--- ```lua 80--- event.on_tick(function(e) 81--- for _, task in pairs(on_tick_n.retrieve(e.tick) or {}) do 82--- if task == "say_hi" then 83--- game.print("Hello there!") 84--- elseif task == "order_66" then 85--- for _, player in pairs(game.players) do 86--- player.die() 87--- end 88--- end 89--- end 90--- end) 91--- ``` 92--- @alias flib.OnTickNTasks table<number, any> 93 94return on_tick_n