C函數lua_gettop將返回傳遞給C函數的參數數量。您必須從堆棧中讀取所有內容並將它們存儲在C數據結構中,或將它們放入Lua註冊表中(請參閱Registry和luaL_ref),並存儲對它們的引用以備將來使用。下面的示例程序使用註冊表方法。
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>
#include <stdlib.h>
/* this function prints the name and extra variables as a demonstration */
static void
TheConstructor(lua_State *L, const char *name, int *registry, int n)
{
int i;
puts(name);
for (i = 0; i < n; ++i) {
lua_rawgeti(L, LUA_REGISTRYINDEX, registry[i]);
puts(lua_tostring(L, -1));
}
free(registry);
}
static int
CreateEntity(lua_State *L)
{
const char *NAME = luaL_checkstring(L, 1);
int *registry;
int i, n;
/* remove the name parameter from the stack */
lua_remove(L, 1);
/* check how many arguments are left */
n = lua_gettop(L);
/* create an array of registry entries */
registry = calloc(n, sizeof (int));
for (i = n; i > 0; --i)
registry[i-1] = luaL_ref(L, LUA_REGISTRYINDEX);
TheContructor(L, NAME, registry, n);
return 0;
}
int
main(int argc, char **argv[])
{
const char TEST_CHUNK[] =
"CreateEntity('foo', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)";
lua_State *L;
L = luaL_newstate();
lua_register(L, "CreateEntity", CreateEntity);
luaL_dostring(L, TEST_CHUNK);
lua_close(L);
return EXIT_SUCCESS;
}
添加lua標記,因爲實際上有一些追隨者。 – BMitch 2011-03-27 13:34:43
爲#lua追隨者而歡呼! ;) – sbk 2011-03-27 14:37:18
你在C或C++嗎? – Puppy 2011-03-27 20:42:00