slot based allocator for lua, usage of lua_createtable
This commit is contained in:
@ -43,6 +43,50 @@ static int physfs_loader(lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
/* WARN! experimental and will probably be removed */
|
||||
/* it was an attempt to ease memory usage problems posed by using lua */
|
||||
/* it saved ~100MiB, but it still hogs ~500MiB for no reason on my PC */
|
||||
static void *custom_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
|
||||
(void)ud;
|
||||
|
||||
/* small allocations are placed in slots, as there's a big chance they will not need to be resized */
|
||||
static char slots[1024][64];
|
||||
static int16_t free_slots[1024] = { [0] = -1 };
|
||||
static size_t free_slot_count = 1024;
|
||||
|
||||
if (free_slots[0] == -1)
|
||||
for (int i = 0; i < 1024; i++)
|
||||
free_slots[i] = (int16_t)i;
|
||||
|
||||
if (nsize == 0) {
|
||||
if (ptr && (char *)ptr >= &slots[0][0] && (char *)ptr <= &slots[1024-1][64-1])
|
||||
free_slots[free_slot_count++] = (int16_t)(((uintptr_t)ptr - (uintptr_t)slots) / 64);
|
||||
else
|
||||
SDL_free(ptr);
|
||||
return NULL;
|
||||
} else {
|
||||
if (!ptr && nsize <= 64 && free_slot_count > 0) {
|
||||
/* use a slot */
|
||||
return slots[free_slots[--free_slot_count]];
|
||||
}
|
||||
|
||||
if ((char *)ptr >= &slots[0][0] && (char *)ptr <= &slots[1024-1][64-1]) {
|
||||
/* still fits */
|
||||
if (nsize <= 64)
|
||||
return ptr;
|
||||
|
||||
/* move from slot to dynamic memory */
|
||||
void *mem = SDL_malloc(nsize);
|
||||
SDL_memcpy(mem, ptr, osize);
|
||||
free_slots[free_slot_count++] = (int16_t)(((uintptr_t)ptr - (uintptr_t)slots) / 64);
|
||||
return mem;
|
||||
}
|
||||
|
||||
return SDL_realloc(ptr, nsize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void game_tick(void) {
|
||||
if (ctx.initialization_needed) {
|
||||
if (!ctx.udata)
|
||||
@ -57,6 +101,8 @@ void game_tick(void) {
|
||||
}
|
||||
state->L = luaL_newstate();
|
||||
|
||||
lua_setallocf(state->L, custom_alloc, NULL);
|
||||
|
||||
/* fakey version of luaL_openlibs() that excludes file i/o and os stuff */
|
||||
{
|
||||
static const luaL_Reg loaded_libs[] = {
|
||||
@ -79,7 +125,7 @@ void game_tick(void) {
|
||||
|
||||
/* package.searchers = { physfs_loader } */
|
||||
lua_getglobal(state->L, "package");
|
||||
lua_newtable(state->L);
|
||||
lua_createtable(state->L, 0, 1);
|
||||
lua_setfield(state->L, -2, "searchers");
|
||||
|
||||
lua_getfield(state->L, -1, "searchers");
|
||||
|
Reference in New Issue
Block a user