How to efficiently schedule a future event for a future tick?

Place to get help with not working mods / modding interface.
Sapphire
Manual Inserter
Manual Inserter
Posts: 3
Joined: Mon Jun 27, 2016 10:23 pm
Contact:

How to efficiently schedule a future event for a future tick?

Post by Sapphire »

Is it possible to tell the game to raise an event (or run a function) on a specific future tick (without using `on_tick` events)?
Use case
I want to have an entity perform an action, then perform that action again later after a (random) number of ticks. Multiple entities will be doing this, so will be possible that more than one will be doing this one the same tick. (To be very specific I want to give the cats in my mod the ability to swipe items off of belts every once in a while.)
Current Solution
I maintain a table of desired future "happenings" (they are not actual events, just function calls), and then check whether the current tick is in there every tick, that will look something like this:

Code: Select all

storage.future_happenings = {
  SOME_TICK_NUMBER = {
    happening_1 = [...],
    happening_2 = [...]
  },
  ANOTHER_TICK = {
    happening_3 = [...]
  },
  [...]
}
And a `on_tick` event handler that looks like this:

Code: Select all

script.on_event(defines.events.on_tick, function(event)
  if storage.future_happenings[event.tick] then
    for _, happening in pairs(storage.future_happenings[event.tick]) do
      [...] -- Do the thing I want to do
    end
      storage.future_happenings[event.tick] = nil -- Remove it, since we're done with it
  end
end
Question
Maybe what I have here is performant enough, but is there some way to tell the game to raise a custom event at a future time, so that I don't need to keep checking if it is that time yet? I could, of course, have this code run on every nth tick with some loss of granularity, but I was wondering if there was a cleaner solution.
User avatar
DaveMcW
Smart Inserter
Smart Inserter
Posts: 3740
Joined: Tue May 13, 2014 11:06 am
Contact:

Re: How to efficiently schedule a future event for a future tick?

Post by DaveMcW »

events.on_tick is very cheap, don't worry about calling it every tick.

Of course you should try to minimize the work you do every tick. Reading a single table index is a great way to do it.
Post Reply

Return to “Modding help”