When you create Lua states, you have the option to pass in an allocator when you use lua_newstate
(as against lua_open
or luaL_newstate
). Normally the allocator would just get a request similar to a realloc
call. But you have the option to pass in a user defined pointer (the first arg) to the allocator.
You can pass the same allocator to two lua state create functions. Just before you create the global table(s) that you want to be shared, you just set the user defined pointer. Then you can return the reference to the same memory location to both the lua states. You wouldn't need any special code to share them. Sample code below:
static char giant_shared_block[1000000];
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
if (nsize == 0) {
if(ptr != giant_shared_block && osize != 0)
free(ptr);
return NULL;
}
else{
int is_shared = *((int *)ud);
if(is_shared){ //indicated by the user prior to creating global memory block in a lua state
*ud = 0; //unset the flag
return giant_shared_block;
}
else if(osize == 0)
return malloc(nsize);
else
return realloc(ptr, nsize);
}
}
Of course the onus on the user to make sure to set the 'shared' flag before creating the table. The first memory allocation after the flag is set, will be shared.