lua-users home
lua-l archive

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


Since Lua 4.0, I have had to patch lmem.c and lua.h to replace the
built-in realloc() and free() allocation technique with one supported by
Amped (since Amped employs its own memory management scheme).  I have
made the following changes to lmem.c and lua.h.  I would ask that the
Lua team consider inclusion of an approach similar to this so I don't
have to directly modify the Lua source.  Note that it is not practical
for me to try and take advantage of the l_realloc and l_free approach,
since the Lua .lib file I use is precompiled and must run in several
applications.  The callback approach is far better, IMO.  (Yes, I know
the code doesn't follow the Lua naming conventions... that should be
corrected.)

Thanks,
Joshua Jensen
Amped: Freestyle Snowboarding
http://www.xbox.com/Games/sports/amped.htm

lmem.c
========
I added:

static void* luaHelper_Realloc(void* ptr, int size)
{
	return realloc(ptr, size);
}


static void luaHelper_Free(void* ptr)
{
	free(ptr);
}


LuaHelper_Realloc s_luaHelper_Realloc = luaHelper_Realloc;
LuaHelper_Free s_luaHelper_Free = luaHelper_Free;


void LuaSetMemoryFunctions(LuaHelper_Realloc reallocFunc, LuaHelper_Free
freeFunc)
{
	if (reallocFunc)
		s_luaHelper_Realloc = reallocFunc;
	else
		s_luaHelper_Realloc = luaHelper_Realloc;

	if (freeFunc)
		s_luaHelper_Free = freeFunc;
	else
		s_luaHelper_Free = luaHelper_Free;
}


I changed the top of luaM_realloc() to:

void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem
size) {
  if (size == 0) {
//    l_free(block, oldsize);  /* block may be NULL; that is OK for free
*/
    (*s_luaHelper_Free)(block);
    block = NULL;
  }
  else if (size >= MAX_SIZET)
    luaD_error(L, l_s("memory allocation error: block too big"));
  else {
//    block = l_realloc(block, oldsize, size);
    block = (*s_luaHelper_Realloc)(block, size);



===================
lua.h
===================
I added:

typedef void* (*LuaHelper_Realloc)(void* ptr, int size);
typedef void (*LuaHelper_Free)(void* ptr);
void LuaSetMemoryFunctions(LuaHelper_Realloc reallocFunc, LuaHelper_Free
freeFunc);