Page 1 of 1
OnTick performance question
Posted: Wed Jul 15, 2015 7:53 am
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?
Re: OnTick performance question
Posted: Wed Jul 15, 2015 10:00 am
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
Re: OnTick performance question
Posted: Wed Jul 15, 2015 1:52 pm
by GotLag
How do I correctly initialise a global table?
Re: OnTick performance question
Posted: Wed Jul 15, 2015 7:12 pm
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
Re: OnTick performance question
Posted: Wed Jul 15, 2015 8:15 pm
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.
Re: OnTick performance question
Posted: Thu Jul 16, 2015 3:23 am
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.