Lifespan of globals created when using /c console command?

Place to get help with not working mods / modding interface.
HeliGungir
Inserter
Inserter
Posts: 24
Joined: Thu Oct 31, 2024 4:43 am
Contact:

Lifespan of globals created when using /c console command?

Post by HeliGungir »

I was looking at https://wiki.factorio.com/Console and noticed some snippets define locals while others define globals.

Eg. global:

Code: Select all

/c surface = game.player.surface
for _, ore in pairs(surface.find_entities_filtered({type="resource"})) do
    ore.amount = 10000
end
vs. local:

Code: Select all

/c local surface = game.player.surface
for _, ore in pairs(surface.find_entities_filtered({type="resource"})) do
    ore.amount = 10000
end
What is the lifespan of globals and locals created by scripts that are executed with the /c command? Is the first version bad practice?

---

Separate question: Why have a variable at all?

Code: Select all

/c for _, ore in pairs(game.player.surface.find_entities_filtered({type="resource"})) do
    ore.amount = 10000
end
Am I overlooking something? It is my understanding that pairs() is only evaluated once, returning a local table that only the For statement can interact with. The For statement iterates over the key-value pairs of the table, providing access to them as _ and ore, then the table is freed upon reaching the closing end. I'm not seeing a good reason to store game.player.surface in a variable here.
Osmo
Fast Inserter
Fast Inserter
Posts: 100
Joined: Wed Oct 23, 2024 12:08 pm
Contact:

Re: Lifespan of globals created when using /c console command?

Post by Osmo »

local scope is only within that command (or less)
I don't remember whether global is permanent or lasts until you reload the save.
But all code snippets you provided do the same thing. In this case variables are optional.
Rseding91
Factorio Staff
Factorio Staff
Posts: 15896
Joined: Wed Jun 11, 2014 5:23 am
Contact:

Re: Lifespan of globals created when using /c console command?

Post by Rseding91 »

'global' variables persist until the map is unloaded (exit to main menu). They also won't persist if someone joins a multiplayer game in progress - a cause of multiplayer desyncs and why persistent values are supposed to be put into the 'storage' variable which does persist through save/load.
If you want to get ahold of me I'm almost always on Discord.
Post Reply

Return to “Modding help”