lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Here's an idea...  It's a bit lame, but I'm wondering if it could work.
Looking at lua_dump(), it will barf unless it's given a Lua function on the stack.  So...
What if I called lua_load on a file that contained "return {}", which just returns an empty table.  Then, I might be able to replace the table value returned by this function with the table I want to serialize out.  That might require some Lua hacking.
I'm starting to lean now more towards writing a simple function that traverses a given table and simply writes out the Lua code that I want.  On second thought, it might not be that hard or take that long to do.

Date: Mon, 8 Apr 2013 12:40:21 -0600
Subject: lua_dump/lua_load

Hi all,
I'm trying to understand Lua's ability to serialize and unserialize a table to a file.  I've started with a Lua file that simply returns a table.  I can load this file as an executable function on the stack, then execute this function to get the table on the stack.  Now here's the question: If I later create a table on the stack, can I somehow, using the C API, create a Lua function that returns this table, and then call lua_dump to serialize the table back out to a file?  I'm having trouble figuring out how to create the function.  I'm tempted to create a C-function and push that onto the stack, but I somehow doubt that that's going to work.  When that C-function is dumped out, I'm not sure what Lua will produce.  At best, I think it would produce an identity function -- one that just returns its given argument.  The C-function doesn't really know anything about the table I'm trying to dump out.
Anyhow, I believe that there has to be a way to do this without doing what I believe would be ridiculous, which would be to write some code that traverses a given table and simply writes out the Lua code.  That would work, but it would be dumb to do if Lua could have already done this for me, had I simply known how to create the function on the stack that returns the table, and it's a lot of work, and it's work that breaks when/if Lua changes.  Call me picky, but I also don't want to go download and incorporate a table serializer that someone else has already written.  I'm trying to own all my code, except for Lua, of course.
Am I making any sense here?  It seems like if I've got the Lua table on the stack, then I'm just a short distance away from being able to somehow call lua_dump to write it out to a file.  I'm just not sure how to create the Lua function.
Also, does lua_dump somehow support the "mode" feature that lua_load does?  Can lua_dump write out human readable Lua code, or is it alway going to be binary?