Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Created June 22, 2018 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudwu/ddd64afbc09aad55b6e8c99ee3c91aeb to your computer and use it in GitHub Desktop.
Save cloudwu/ddd64afbc09aad55b6e8c99ee3c91aeb to your computer and use it in GitHub Desktop.
unpack lua table { ... }
// 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