Created
June 22, 2018 07:19
-
-
Save cloudwu/ddd64afbc09aad55b6e8c99ee3c91aeb to your computer and use it in GitHub Desktop.
unpack lua table { ... }
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Unpack lua table create by { ... } | |
#define LUA_LIB | |
#include <lua.h> | |
#include <lauxlib.h> | |
static int | |
max_index(lua_State *L, int index) { | |
int n = lua_rawlen(L, index); | |
if (n == 0) { | |
lua_pushnil(L); | |
} else { | |
lua_pushinteger(L, n); | |
} | |
while (lua_next(L, index) != 0) { | |
lua_pop(L, 1); | |
int key = luaL_checkinteger(L, -1); | |
if (key > n) { | |
n = key; | |
} | |
} | |
return n; | |
} | |
static int | |
lunpack(lua_State *L) { | |
luaL_checktype(L, 1, LUA_TTABLE); | |
int n = max_index(L, 1); | |
int i; | |
luaL_checkstack(L, n, NULL); | |
for (i=0;i<n;i++) { | |
lua_rawgeti(L, 1, i+1); | |
} | |
return n; | |
} | |
LUAMOD_API int | |
luaopen_tableunpack(lua_State *L) { | |
luaL_checkversion(L); | |
luaL_Reg l[] = { | |
{ "unpack", lunpack }, | |
{ NULL, NULL }, | |
}; | |
luaL_newlib(L, l); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment