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?
OnTick performance question
Re: OnTick performance question
You'll have to register different events, namely: onbuiltentity, onrobotbuiltentity
then in your ontick function, do something like:
In theory this should work, haven't tested it, but it's similar to what i'm doing
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)
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
Re: OnTick performance question
How do I correctly initialise a global table?
-
- Fast Inserter
- Posts: 157
- Joined: Fri Jun 26, 2015 11:13 pm
Re: OnTick performance question
Use the oninit event.GotLag wrote:How do I correctly initialise a global table?
Code: Select all
if(nil == glob.yourTable) then
glob.yourTable = {};
end
Re: OnTick performance question
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: Mostly the same as johans , but in one line.
I like to init my tables like that:
Code: Select all
glob.yourTable = glob.yourTable or {}
Re: OnTick performance question
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.