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

Place to get help with not working mods / modding interface.
Post Reply
doktorstick
Fast Inserter
Fast Inserter
Posts: 152
Joined: Fri Aug 12, 2016 10:22 pm
Contact:

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

Post 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.

User avatar
DaveMcW
Smart Inserter
Smart Inserter
Posts: 3700
Joined: Tue May 13, 2014 11:06 am
Contact:

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

Post 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)

doktorstick
Fast Inserter
Fast Inserter
Posts: 152
Joined: Fri Aug 12, 2016 10:22 pm
Contact:

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

Post 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.

User avatar
DaveMcW
Smart Inserter
Smart Inserter
Posts: 3700
Joined: Tue May 13, 2014 11:06 am
Contact:

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

Post 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

User avatar
Adil
Filter Inserter
Filter Inserter
Posts: 945
Joined: Fri Aug 15, 2014 8:36 pm
Contact:

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

Post 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?
I do mods. Modding wiki is friend, it teaches how to mod. Api docs is friend too...
I also update mods, some of them even work.
Recently I did a mod tutorial.

Post Reply

Return to “Modding help”