Lua的C API:处理和存储的其他参数 [英] Lua C API: Handling and storing additional arguments

查看:117
本文介绍了Lua的C API:处理和存储的其他参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CreateEntity是我必然的Lua在我的项目的C函数。这需要一个实体类名字符串作为第一个参数,任意数量的,应获得通过所选择的实体的构造额外的参数。

CreateEntity is a C function I bound to Lua in my project. It takes an entity class name string as first argument, and any number of additional arguments which should get passed to the constructor of the chosen entity.

例如,如果CreateEntity是一个正​​常的Lua的功能,我可以这样做:

For example, if CreateEntity was a normal Lua function I could do it this way:

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

但我怎么能做到这一点与C Lua的功能?

But how can I do this with a C Lua function?

推荐答案

C函数的 lua_gettop 将返回多少参数传递给C函数。您必须全部从堆栈中阅读这些并将其存储在C的数据结构,或者将它们放置在Lua的登记处(见的注册表 luaL_ref ),并存储对它们的引用供以后使用。下面的示例程序使用注册表的方法。

The C function lua_gettop will return how many parameters were passed to your C function. You must either read these all from the stack and store them in a C data structure, or place them in the Lua registry (see Registry and luaL_ref) and store references to them for later use. The example program below uses the registry approach.

#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的C API:处理和存储的其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆