1+ --- Schedule tasks to be executed later.
2+ -- @module on-tick-n
3+ -- @alias on_tick_n
4+ -- @usage local on_tick_n = require("__flib__.on-tick-n")
5+
16local on_tick_n = {}
27
8+ --- Initialize the module's script data table.
9+ -- Must be called at the **beginning** of `on_init`. Can also be used to delete all current tasks.
310function on_tick_n .init ()
411 if not global .__flib then
512 global .__flib = {}
613 end
714 global .__flib .on_tick_n = {}
815end
916
17+ --- Retrieve the tasks for the given tick.
18+ -- @tparam number tick
19+ -- @treturn Tasks|nil The tasks to execute on this tick, or `nil`.
1020function on_tick_n .retrieve (tick )
1121 -- Failsafe for rare cases where on_tick can fire before on_init
1222 if not global .__flib or not global .__flib .on_tick_n then return end
@@ -17,19 +27,25 @@ function on_tick_n.retrieve(tick)
1727 end
1828end
1929
20- function on_tick_n .add (tick , action )
30+ --- Add a task to execute on the given tick.
31+ -- @tparam number tick
32+ -- @tparam any task The data representing this task. This can be anything that is not a function.
33+ -- @treturn TaskIdent An identifier for the task. Save this if you might remove the task before execution.
34+ function on_tick_n .add (tick , task )
2135 local list = global .__flib .on_tick_n
2236 local tick_list = list [tick ]
2337 if tick_list then
2438 local index = # tick_list + 1
25- tick_list [index ] = action
39+ tick_list [index ] = task
2640 return {index = index , tick = tick }
2741 else
28- list [tick ] = {action }
42+ list [tick ] = {task }
2943 return {index = 1 , tick = tick }
3044 end
3145end
3246
47+ --- Remove a scheduled task.
48+ -- @tparam TaskIdent ident The identifier object for the task, as returned from @{on-tick-n.add}.
3349function on_tick_n .remove (ident )
3450 local tick_list = global .__flib .on_tick_n [ident .tick ]
3551 if not tick_list or not tick_list [ident .index ] then return false end
@@ -39,4 +55,16 @@ function on_tick_n.remove(ident)
3955 return true
4056end
4157
58+ --- Concepts
59+ -- @section
60+
61+ --- A unique identifier for a previously added task, used in @{on-tick-n.remove}.
62+ -- @tfield number tick The tick this task is scheduled for.
63+ -- @tfield number index The tasks' index in the tick's @{Tasks} table.
64+ -- @Concept TaskIdent
65+
66+ --- An table of @{TaskIdent}s, representing the tasks to be executed on a given tick.
67+ -- **This is not an array, there may be gaps. Always use `pairs` to iterate this table.**
68+ -- @Concept Tasks
69+
4270return on_tick_n
0 commit comments