Files
integration/luprex/syscpp/lpx-table.cpp

44 lines
1.0 KiB
C++
Raw Normal View History

2020-11-13 18:17:47 -05:00
#include "lpx-table.hpp"
// Clear the table. Removes metatable and all key-value pairs.
int lpx_table_clear(lua_State *L) {
const int tab = lua_gettop(L);
luaL_checktype(L, tab, LUA_TTABLE);
// Clear the metatable.
lua_pushnil(L);
lua_setmetatable(L, tab);
// Clear the elements.
lua_pushnil(L);
while (lua_next(L, tab) != 0) {
lua_pop(L, 1); // Pop the old value.
lua_pushvalue(L, -1); // Clone the key
lua_pushnil(L); // Push the new value.
lua_settable(L, tab);
}
// Remove the arguments and return nothing.
lua_remove(L, tab);
return 0;
}
int lpx_table_coerce(lua_State *L) {
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
lua_newtable(L);
}
return 1;
}
static const struct luaL_Reg lpx_table_lib [] = {
{"clear", lpx_table_clear},
{"coerce", lpx_table_coerce},
{NULL, NULL} /* sentinel */
};
int luaopen_lpx_table (lua_State *L) {
luaL_openlib(L, "table", lpx_table_lib, 0);
return 1;
}