Trouble Serializing a Table for Storage

Posted by Noredil on Tue 12 Feb 2008 08:47 PM — 4 posts, 19,758 views.

#0
I've been poking around on the forums here, learning how to serialize variables I'll need to use across sessions. I found an example in another thread which seemed to do exactly what I needed, but I get a runtime error trying to duplicate it.

I created this simple alias to play around with and try and get this to work. Here's the current alias and the error I'm getting.

function setvar()
luaenemies = {billy, bob}
require "serialize"
SetVariable("enemylist", serialize('luaenemies'))
end

And the error...

Run-time error
Plugin: LidSys (called from world: Achaea)
Function/Sub: setvar called by alias
Reason: processing alias ""
...\worlds\plugins\MyAchaea\modules\scripts\enemies.lua:26: attempt to call global 'serialize' (a table value)
stack traceback:
...\worlds\plugins\MyAchaea\modules\scripts\enemies.lua:26: in function <...\worlds\plugins\MyAchaea\modules\scripts\enemies.lua:21>

Any ideas why this won't work for me?
USA #1
Your quotes are all in funky places, unless "billy" and "bob" are variables and not strings, and "luaenemies" is a string and not a variable.

function setvar()
  luaenemies = { "billy", "bob" }
  require "serialize"
  SetVariable("enemylist", serialize( luaenemies ) )
end
Australia Forum Administrator #2
You actually need to call something in the serialize table. Try this:


require "serialize"

luaenemies = { "billy", "bob" }
SetVariable("enemylist", "luaenemies = " .. serialize.save_simple ( luaenemies ) )


This calls "save_simple" inside the serialize table, to set the variable (which now looks like this):


luaenemies = {
  [1] = "billy",
  [2] = "bob",
  }


And to get it back next time:


assert (loadstring (GetVariable ("enemylist"))) () 


That loads the string back into the Lua variable luaenemies.
#3
Finally got it nailed down. Thanks guys, it looks like my quotes were what was really throwing me off. Serialize didn't do quite what I wanted it to, so I ended up doing a SetVariable with a table.concat and pipes to get it lined up.