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

标签 c++ c lua lua-api

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/

相关文章:

c++ - "#include&lt"和#include之间的区别”

c++ - 嵌入 wxWidgets 的简单 Lua 解释器

mobile - 将函数作为变量传递并将其分配给仍然能够在 Lua 中引用 "self"的对象

C++ 禁用忙碌/等待光标

c++ - 对任意大的位数组或数字进行位操作

c++ - 使用 libCurl API 请求初级指导

c - stat st_mode 始终等于 16877

c - 如何检测用户输入是 while 循环中的 [ Control ] + [ D ]

java - jedis llen 结果不等于 redis llen

c++ - 为什么 cursor.clearselection() 在此示例中不起作用?