Save table containing functions to file...

Hey guys, just wondering if this is possible.

I have a table which contains function calls for example :

local nTable = {}  
nTable[1] = spawn(200, 200, "Coin", true)  
nTable[2] = spawn(100, 200, "Coin", true)  

That is just a example of roughly what i am attempting to do. I basically want to save that table to a file and load it per level and have the functions executed once on level startup (basically it fills my levels with objects)

Is this possible or am i going to have to go an alternate route?

Thanks [import]uid: 6981 topic_id: 7402 reply_id: 307402[/import]

you can’t create function calls like that… using the brackets runs the function immediately

try this
[lua]local function spawn(x,y,type,visible)
print(x,y,type,visible)
end

local nTable={}
nTable[1] = {fn=spawn, args={200,200,“Coin”,true}}
nTable[2] = {fn=spawn, args={100,200,“Coin”,true}}

– call functions later
nTable[1].fn(unpack(nTable[1].args))
nTable[2].fn(unpack(nTable[2].args)) [/lua]

also if your function isn’t local, you can use the _G global to call it. (this means you could store the function name as a string externally, which is what you are asking to do)

[lua]function spawn(x,y,type,visible)
print(x,y,type,visible)
end

local nTable={}
nTable[1] = {fn=“spawn”, args={200,200,“Coin”,true}}
nTable[2] = {fn=“spawn”, args={100,200,“Coin”,true}}

– call functions later
_GnTable[1].fn
_GnTable[2].fn [/lua]

i haven’t worked out how you would do this with local functions yet. or how to store the whole thing as a string, including the args

is ‘loadstring’ command available in corona?

this works at: http://www.lua.org/cgi-bin/demo

[lua]function spawn(x,y,type,visible)
print(x,y,type,visible)
end

local nTable={}
nTable[1] = {fn=“spawn”, args=“200,200,‘Coin’,true”}
nTable[2] = {fn=“spawn”, args=“100,200,‘Coin’,true”}

– call functions later
assert(loadstring(nTable[1].fn…"("…nTable[1].args…")"))()
assert(loadstring(nTable[2].fn…"("…nTable[2].args…")"))()[/lua]

to use full strings try this… although i really don’t know if it’s messing up memory as I can’t define the stringed variables/functions as local

[lua]function spawn(x,y,type,visible)
print(x,y,type,visible)
end

local nTable={}

nTable[1] = “fn=spawn; args={200,200,“Coin”,true}”
nTable[2] = “fn=spawn; args={100,200,“Coin”,true}”
nTable[3] = “spawn(300,300,“Cat”, true)”

assert(loadstring(nTable[1]))()
fn(unpack(args))

assert(loadstring(nTable[2]))()
fn(unpack(args))

– another method
assert(loadstring(nTable[3]))()[/lua] [import]uid: 6645 topic_id: 7402 reply_id: 26139[/import]

Thanks man :slight_smile:

Will give that a try, appreciate the response [import]uid: 6981 topic_id: 7402 reply_id: 26282[/import]