From 0e083ba8d662aed47006be95b5189eabf6629a61 Mon Sep 17 00:00:00 2001 From: JugadorXEI Date: Mon, 17 Mar 2025 19:38:57 +0100 Subject: [PATCH] Expose footsteps[], footsteps.iterate and #footsteps to Lua --- src/lua_terrainlib.c | 79 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/src/lua_terrainlib.c b/src/lua_terrainlib.c index 7588992d8..25aaaf706 100644 --- a/src/lua_terrainlib.c +++ b/src/lua_terrainlib.c @@ -304,6 +304,75 @@ static int footstep_num(lua_State *L) return 1; } +static int lib_iterateFootsteps(lua_State *L) +{ + size_t i; + + if (lua_gettop(L) < 2) + { + lua_pushcfunction(L, lib_iterateFootsteps); + return 1; + } + + lua_settop(L, 2); + lua_remove(L, 1); // state is unused. + + if (!lua_isnil(L, 1)) + i = K_GetFootstepHeapIndex(*(t_footstep_t **)luaL_checkudata(L, 1, META_FOOTSTEP)) + 1; + else + i = 0; + + // footsteps are always valid, only added, never removed + if (i < K_GetNumFootstepDefs()) + { + LUA_PushUserdata(L, K_GetFootstepByIndex(i), META_FOOTSTEP); + return 1; + } + + return 0; +} + +static int lib_getFootstep(lua_State *L) +{ + const char *field; + size_t i; + + // find footstep by number + if (lua_type(L, 2) == LUA_TNUMBER) + { + i = luaL_checkinteger(L, 2); + if (i >= K_GetNumFootstepDefs()) + return luaL_error(L, "footsteps[] index %d out of range (0 - %d)", i, K_GetNumFootstepDefs()-1); + LUA_PushUserdata(L, K_GetFootstepByIndex(i), META_FOOTSTEP); + return 1; + } + + field = luaL_checkstring(L, 2); + + // special function iterate + if (fastcmp(field,"iterate")) + { + lua_pushcfunction(L, lib_iterateFootsteps); + return 1; + } + + // find footstep by name + t_footstep_t *byname = K_GetFootstepByName(field); + if (byname != NULL) + { + LUA_PushUserdata(L, byname, META_FOOTSTEP); + return 1; + } + + return 0; +} + +static int lib_numFootsteps(lua_State *L) +{ + lua_pushinteger(L, K_GetNumFootstepDefs()); + return 1; +} + static int overlay_get(lua_State *L) { t_overlay_t *overlay = *((t_overlay_t **)luaL_checkudata(L, 1, META_OVERLAY)); @@ -626,6 +695,16 @@ int LUA_TerrainLib(lua_State *L) lua_pushcfunction(L, footstep_num); lua_setfield(L, -2, "__len"); lua_pop(L,1); + + lua_newuserdata(L, 0); + lua_createtable(L, 0, 2); + lua_pushcfunction(L, lib_getFootstep); + lua_setfield(L, -2, "__index"); + + lua_pushcfunction(L, lib_numFootsteps); + lua_setfield(L, -2, "__len"); + lua_setmetatable(L, -2); + lua_setglobal(L, "footsteps"); luaL_newmetatable(L, META_OVERLAY); lua_pushcfunction(L, overlay_get);