OnTick performance question

Place to get help with not working mods / modding interface.
GotLag
Filter Inserter
Filter Inserter
Posts: 534
Joined: Sat May 03, 2014 3:32 pm
Contact:

OnTick performance question

Post by GotLag »

I have some logic I'd like to run on a certain type of entity every tick, what's the most performance-friendly way of going about this?
My guess is creating some kind of persistent array of all the entities of that type, and updating it when one is built or destroyed/removed, so as not to recreate the array each tick, but how would I go about this? Lua is not my forte.

Or am I missing something and there's a better way?
Choumiko
Smart Inserter
Smart Inserter
Posts: 1352
Joined: Fri Mar 21, 2014 10:51 pm
Contact:

Re: OnTick performance question

Post by Choumiko »

You'll have to register different events, namely: onbuiltentity, onrobotbuiltentity

Code: Select all

function onbuiltentity(event)
  local ent = event.createdentity
  local cname = ent.name
  if cname == "yourEntityname"
      table.insert(glob.yourTable, ent)
  end
end
game.onevent(defines.events.onbuiltentity, onbuiltentity)
game.onevent(defines.events.onrobotbuiltentity, onbuiltentity)
then in your ontick function, do something like:

Code: Select all

for i=#glob.yourTable, 1, -1 do
  if glob.yourTable[i].valid then
    --do your stuff
  else -- entity is invalid (destroyed, mined), remove it
    glob.yourTable[i] = nil
  end
end
In theory this should work, haven't tested it, but it's similar to what i'm doing
GotLag
Filter Inserter
Filter Inserter
Posts: 534
Joined: Sat May 03, 2014 3:32 pm
Contact:

Re: OnTick performance question

Post by GotLag »

How do I correctly initialise a global table?
johanwanderer
Fast Inserter
Fast Inserter
Posts: 157
Joined: Fri Jun 26, 2015 11:13 pm

Re: OnTick performance question

Post by johanwanderer »

GotLag wrote:How do I correctly initialise a global table?
Use the oninit event.

Code: Select all

if(nil == glob.yourTable) then
  glob.yourTable = {};
end
Choumiko
Smart Inserter
Smart Inserter
Posts: 1352
Joined: Fri Mar 21, 2014 10:51 pm
Contact:

Re: OnTick performance question

Post by Choumiko »

You can/should also add it to the onload event. That way your mod can be added to an existing save.
I like to init my tables like that:

Code: Select all

glob.yourTable = glob.yourTable or {}
Mostly the same as johans , but in one line.
GotLag
Filter Inserter
Filter Inserter
Posts: 534
Joined: Sat May 03, 2014 3:32 pm
Contact:

Re: OnTick performance question

Post by GotLag »

While I'm asking questions, is the fluid tick different from the regular tick? I think I remember reading something to that effect, but I can't find documentation for it. The listed fluid consumption for a steam engine is 0.1 per tick, but in-game it appears to be at about 1/10 that speed.
Post Reply

Return to “Modding help”