lua-users home
lua-l archive

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


On Fri, 18 Feb 2005 12:32:22 +0100, Dino Patti <dino@mediamobsters.com> wrote:
> 
> Hi,
> 
> I'm trying to serialize(persist) and deserialize(unpersist) a lua state
> using the Pluto lib. It seems to work fine (got good help from the author).
> 
> But now I face a difficult task. I have to start(resume) the same place
> where I left(yielded) the original script I serialized.
> The script contains many yields and resumes, and I want to start the script
> again as if it wasn't persisted/unpersisted but it just resumed.

The key here is that in order to save a thread including its execution
position, that thread _must_ be yielded. There's a lot of different
ways to accomplish this, based on how your control flows, but if
you're not really making use of coroutines otherwise, probably the
simplest way is to run the main script _as_ a coroutine with
lua_newthread. Then, in a loop, resume the thread, and when it returns
from the resume (by yielding from the script) check what value is
returned by the yield. For instance (this code is purely from memory):

enum
{
    SIGNAL_CONTINUE = 0,
    SIGNAL_SAVEANDCONTINUE = 1,
    SIGNAL_EXIT = 2
};

lua_State *L2 = lua_createthread(...);
while(true)
{
    lua_resume(L2, 0);
    int signal = lua_tonumber(L2, -1);
    lua_pop(L2, 1);
    switch(signal)
    {
    case SIGNAL_CONTINUE:
        break;
    case SIGNAL_SAVEANDCONTINUE:
        // do pluto persistence
        break;
    case SIGNAL_SAVEANDEXIT:
        // clean up and exit
        break;
    }
}

In the script, you can call yield(0) to simply do nothing (it's
unclear why you'd want to do this), yield(1) to save the state and
continue execution, or yield(2) to exit.

Ben