gpt4 book ai didi

c++ - Lua C API : Handling and storing additional arguments

转载 作者:太空狗 更新时间:2023-10-29 20:47:30 25 4
gpt4 key购买 nike

CreateEntity 是我在项目中绑定(bind)到 Lua 的 C 函数。它采用实体类名称字符串作为第一个参数,以及应传递给所选实体的构造函数的任意数量的附加参数。

例如,如果 CreateEntity 是一个普通的 Lua 函数,我可以这样做:

function CreateEntity( class, ... )  
-- (choose a constructor function based on class)
args = {...}
-- (store args somewhere for whatever reason)
TheConstructor( ... )
end

但是我怎样才能用 C Lua 函数来做到这一点呢?

最佳答案

C 函数 lua_gettop将返回传递给您的 C 函数的参数数量。您必须从堆栈中读取所有这些并将它们存储在 C 数据结构中,或者将它们放在 Lua 注册表中(参见 RegistryluaL_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;
}

关于c++ - Lua C API : Handling and storing additional arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5448654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com