Page 1 of 1

closures are not saved (0.12.29)

Posted: Sun Apr 03, 2016 8:06 pm
by Impatient
maybe it is obvious. to me it was not. maybe now it is. closures are not stored when the game is saved. just want to share my findings.

i did something like this to achieve privacy:

Code: Select all

function initGlobals()
    global = {}
    local internals={}
    internals.nextId = 0
    global.getNextId = function()
        internals.nextId = internals.nextId+1
        return internals.nextId-1
    end
end
internals.nextId being locally available to global.getNextId() is a closure. It works fine in the session when function initGlobals() is executed, but not after a save/load. after a save/load an error is thrown when global.getNextId() is executed. it says something like "Upvalue _EVN is nil." (_EVN is nowhere part of my code and the term "upvalue" is associated with the code structure in the surrounding of the lua script http://www.lua.org/pil/27.3.3.html ) i assume this error is thrown because variable 'internals' is not saved.

so i use this:

Code: Select all

function initGlobals()
    global = {}
    global.__internals={}
    global.__internals.nextId = 0
    global.getNextId = function()
        global.__internals.nextId = global.__internals.nextId+1
        return global.__internals.nextId-1
    end
end
it does not have this neat privacy of nextId, but it works.

this experience makes me think, that i better stay away from closures alltogether when modding for factorio. or at least always make sure very carefully, that the internals are stored somewhere in 'global'. anyone with experiences on that topic?

Re: closures are not saved (0.12.29)

Posted: Sun Apr 03, 2016 8:16 pm
by daniel34
From experimentation, it seems like functions may be serialized as long as they don't contain upvalues (i.e. they aren't closures); Factorio crashes if you call a closure that was persisted across a save.
Source: https://wiki.factorio.com/index.php?tit ... cle#global