Dimitry
Dimitry

Reputation: 2348

Lua make upvalue into constant

The program, I'm writing lua script for, doesn't support saving of upvalues. Hence function fun would not be valid after restoring program state:

gen=function(par)
    local a=par
    return function() print(a) end
    end
fun=gen(2)

On the other hand simple functions without closures like gen are saved and loaded normally. I'd like to create a bunch of functions similar to fun with different values of parameter a in the above. Programmatic equivalent of:

fun1=function()
    local a=1
    print(a)
end
fun2=function()
    local a=2
    print(a)
end
--and so on

Are there possibilities of doing so?

Upvotes: 1

Views: 255

Answers (1)

Henrik Ilgen
Henrik Ilgen

Reputation: 1967

You can create a table that behaves just as your function (but, since it's a table, it should hopefully be restored correctly):

gen = function(par)
    return setmetatable({a = par}, {
            __call = function(self)
                print(self.a)
            end
        })
end

fun = gen(1)  -- Note: fun is a table, but can be called like a function.
fun()

If you need to add parameters to your table-function, you can simply do so by adding parameters to the __call metamethod:

gen = function(par)
    return setmetatable({a = par}, {
            __call = function(self, something)
                print(self.a, something)
            end
        })
end

fun = gen(1)
fun("foobar")   -- Outputs "1   foobar"

Check out the Lua manual, section 'Metatables and Metamethods' for more info!

Upvotes: 1

Related Questions