lua-users home
lua-l archive

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


kathrin_69@gmx.de wrote:
Hello Ben and every buddy else,

I investigated a bit and it seems much simpler: If I call lua_Newstate instead of luaL_Newstate as I did until now, I am able to pass an allocator function which is used exclusively for memory management by Lua regarding the lua_State* it is assigned to.


The default allocator function used by luaL_Newstate() is this:

-----------------------------
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
 (void)ud;
 (void)osize;
 if (nsize == 0) {
   free(ptr);
   return NULL;
 }
 else
   return realloc(ptr, nsize);
}
-----------------------------

If I would overwrite it in a way so that all memory used by my lua_State* is inside my own (pre-allocated) buffer, I could just save and re-load that buffer to/from disc and resume execution. What do you think, will this work? It sounds pretty easy so far.

Two questions to the l_alloc function shown above:
1. What is void* ud for? The src code says something about "auxiliary data to the allocation function". Why is it not used by that function?
It's there for custom allocation functions that need to keep extra state. That state can be stored in memory addressed by ud.

2. What are the first two lines for?
 (void)ud;
 (void)osize;
They do absolutely nothing, right? Are they there to let the compiler check something?

I explained ud above. The osize argument is necessary if the custom memory manager doesn't track the size of each piece of allocated memory the way the standard C malloc function does. In that case, the memory manager needs to be told how much memory to free as well as the address of the memory.

The default allocation function doesn't need to use those two arguments, but a custom allocation function may find them useful.

If you intend to write your own memory manager you may find those arguments useful as well.