> > |
%META:TOPICINFO{author="ElminI" date="1096061815" format="1.0" version="1.1"}%
%META:TOPICPARENT{name="WebHome"}%
At least for now, we are going to attempt to allow saving of the
game by a full dump of state information, including lua data, to file.
This will be difficult, however, since Zippy's state includes data
maintained by both C and Lua code, and since it involves many pointers
and reference loops. To help with this, I've made up a simple
framework for saving such data to file and restoring it.
The file savefile.h defines functions for writing savefiles and reading
them. In this scheme, data to be saved is divided up into "objects,"
which consist of two kinds of information: references to other objects, and
strings of binary data. References are simply C pointers to sections of
memory which represent the objects they refer to in some fashion.
When a savefile is written, the savefile framework keeps track of the size
of each object in memory. It interns objects, assigns them index numbers,
and translates references accordingly.
When a savefile is read, the framework allocates the memory for each object
according to the sizes given in the writing stage and resolves the
references back to C pointers. It then calls a callback for each object,
which is responsible for determining the type of the object and restoring it
using the references and data that were stored with it.
The mapping of C structures to the framework above is relatively
simple, but this is not the case for Lua data, which is not normally referred
to using C pointers. The file luasave.h defines functions that save and
restore lua data. The method employed is to intern each object to be saved,
mapping it to a C pointer to an integer, which is itself a canonical Lua
reference to the object. This pointer is used within the savefile framework
to represent the object and to refer to it.
If a C structure is being saved, and it needs to store a reference to some
Lua data, the appropriate method is as follows:
- Push the Lua value onto the stack.
- Call
save_lua_value() on it.
This will add the Lua data to the file and associate a reference to it with the
C structure in the savefile. When the C structure is to be restored, the
appropriate method of retreiving the Lua reference is as follows:
- Call
read_reference_restoring_first() to restore the Lua data
and retreive a C pointer to a Lua reference to it.
- Call
lua_getref() to push the Lua data onto the stack.
- Make a new Lua reference to the data. Do NOT save or refer to the pointer
or Lua reference returned by
read_reference_restoring_first(), as both will
be released when the restoring process is complete.
-- ElminI - 24 Sep 2004 |