Skip to content

Custom Memory Allocator

kamih edited this page Jul 14, 2012 · 1 revision

By default, Lua will use realloc and free when it needs to get or free memory. If you wish, you can provide a custom allocator by calling LuaUtils::LuaSetAllocFunc (be sure to call this before creating a new LuaState if you want it to use the custom allocator).

To help you write your own allocator or wrapper, the default allocator function used by Lua looks like this:

void *luaAlloc(void *userData, void *ptr, size_t oldSize, size_t newSize)
{
    if (newSize == 0)
    {
        free(ptr);
        return 0;
    }
    else
        return realloc(ptr, newSize);
}

Note that you can query the amount of memory currently allocated (including un-referenced objects that haven’t been collected yet) by calling LuaState::getMemUsage or LuaState::getMemUsageKB.

Clone this wiki locally