Page 1 of 1

Proper way to initialize a cache to "game" table?

Posted: Sat Aug 13, 2016 2:30 am
by doktorstick
Howdy.

What's the proper way to initialize a cache to the game table? I cannot do it in on_load since game doesn't exist, yet. Right now, I've resorted to doing:

Code: Select all

local hacked_cache = nil

script.on_event (
   defines.events.on_tick,
   function (event)
      if hacked_cache == nil then
         build_hacked_cache()
      end
    ...
)
which seems plain wrong.

Thanks for the assist.

Re: Proper way to initialize a cache to "game" table?

Posted: Sat Aug 13, 2016 4:34 am
by DaveMcW
1. Store your cache in global, not game.
2. Initilize it in on_init.

Code: Select all

script.on_init(function()
  global.cache = {}
  global.cache["mycounter"] = 0
end)

Re: Proper way to initialize a cache to "game" table?

Posted: Sat Aug 13, 2016 4:39 am
by doktorstick
Thanks for the response.

Minor misunderstanding. I'm not storing the cache in game; it's in the top-level "local". It's basically a lookup table on some static computations from game.entity.prototypes. Since the data is static and cannot change during run-time, I don't see a need to store it in global unless that's the way things are done in the Factorio modding world.

Re: Proper way to initialize a cache to "game" table?

Posted: Sat Aug 13, 2016 5:16 am
by DaveMcW
Ok, then your solution in the first post is the proper way to do it. You can use a helper function if you want to keep on_tick clean.

Code: Select all

function get_cache()
  if hacked_cache == nil then
    build_hacked_cache()
  end
  return hacked_cache
end

Re: Proper way to initialize a cache to "game" table?

Posted: Mon Aug 15, 2016 6:17 pm
by Adil
Then why are you trying to store what is already stored in `game`?
If your calculations are rare, why bother at all.
If calculations are on_tick I'm still not sure reading from lua table would be better than from userdata, but couldn't you just store the values of variables you need about entities you need?