Problem with loadstring and serializing tables

Posted by Mentallaxative on Sun 23 Dec 2007 03:25 PM — 3 posts, 15,086 views.

#0
Hi there,

I'm trying to make a Lua plugin that counts the number of different animals I hunt on the mud I play. There are well over 100 of them so I thought I would try placing them all into a table.

I've run into a problem with loading the serialized table back during OnPluginInstall.

I get the error:


Description:  [string "Plugin"]:147: [string "{..."]:1: unexpected symbol near '{'

stack traceback:

	[C]: in function 'assert'

	[string "Plugin"]:147: in function <[string "Plugin"]:145>
Called by:    Function/Sub: OnPluginInstall called by Plugin Hunt_Counts

Reason: Executing plugin Hunt_Counts sub OnPluginInstall


The two functions in question are:



function OnPluginInstall ()
hunt={}
assert (loadstring (GetVariable ("hunt") or "")) ()
end -- OnPluginInstall

function OnPluginSaveState ()
require "serialize"
SetVariable ("hunt", serialize.save_simple (hunt))
end -- OnPluginSaveState



The { in [string "{..."] is referring to the serialized variable, which is something like

{
  ["Yellow Alligator"] = 1,
  }


which I found out using GetPluginVariable.
Australia Forum Administrator #1
The serialize.save_simple does not save a variable name, as it doesn't know it (you are passing a table address, not a variable name).

Thus you need to put it back at one end or the other. One way would be:


SetVariable ("hunt", "hunt = " .. serialize.save_simple (hunt))


Or, when you load it back:


assert (loadstring ("hunt = " .. GetVariable ("hunt") or " {}")) ()


(But don't do both).
#2
Thanks, it's working now! :D