Re: object serialization

Szymon Gatner <[email protected]>
Newsgroups gmane.comp.lang.lua.bind.user
Message-ID <[email protected]>
2011/4/22 Jason McKesson <[email protected]>:
> On 4/21/2011 6:28 PM, Szymon Gatner wrote:
>>
>> Hi,
>>
>> what would be the simple and elegant way to do serialization /
>> persistance of a specific luabind::object?
>>
>> I only need to save numeric and string values and tables of them. I
>> was thinking about recursive visitation like so:
>>
>> void visit(const luabind::object&  obj)
>> {
>>   using namespace luabind;
>>
>>   if (type(obj) == LUA_TTABLE)
>>   {
>>     cout<<  "{"<<  endl;
>>
>>     for (luabind::iterator it(obj); it != luabind::iterator(); ++it)
>>     {
>>       if (type(it.key()) == LUA_TSTRING)
>>       {
>>         if (type(*it) != LUA_TTABLE)
>>         {
>>           cout<<  it.key()<<  " = "<<  *it<<  endl;
>>         }
>>         else
>>         {
>>           visit(*it);
>>         }
>>       }
>>     }
>>
>>     cout<<  "}"<<  endl;
>>   }
>> }
>>
>> cout is used here to print name/value pairs but in real case actual
>> persistance code would be used.
>>
>> Am I going the right way?
>>
>> Cheers,
>> Szymon
>
> If the luabind::object is a Lua table, wouldn't the easiest way to serialize
> it be to convert it into a Lua script file? I've included a Lua script I
> wrote which takes an arbitary table (that contains only standard Lua types:
> numbers, tables, arrays, and strings) and writes a file that contains the
> table as a valid Lua script. All you need to do is print "return" to the
> file before calling "WriteTable", and you will get a Lua script. If you call
> "dofile" on this Lua script, it will return the table.
>
> Luabind is *way* overkill for this.
>

Thanks for your answer.

I do like the idea of dumping Lua state data to a valid Lua script, it
solves "deserialization" nicely.

Thing is I don't want to dump that to a file but rather to a C++
ostream which can then be appended to the rest of serialized data or
sent via network etc. In that case would you rather still generate
serialized Lua script in Lua but instead of writing to file use a
string or maybe did it from C/C++?

Why is it overkill? Equivalent C++/luabind code is definitely no
longer than Lua snipped you presented.

Thanks again!

------------------------------------------------------------------------------
Fulfilling the Lean Software Promise
Lean software platforms are now widely adopted and the benefits have been 
demonstrated beyond question. Learn why your peers are replacing JEE 
containers with lightweight application servers - and what you can gain 
from the move. http://p.sf.net/sfu/vmware-sfemails
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.