简体   繁体   English

如何使用表类型参数和表类型返回值从Lua调用C函数?

[英]How to call a C Function from Lua with table type argument and table type return value?

I want to implement a function with C language, this function should be called with an table argument, and it should return a table type value. 我想用C语言实现一个函数,这个函数应该用一个table参数调用,它应该返回一个表类型值。

Normally we implement the function with C for lua like the code blow.But the library doesn't provide the luaL_checktable and lua_pushtable, what can we do? 通常我们使用C实现lua函数,就像代码一样。但是库没有提供luaL_checktable和lua_pushtable,我们能做什么?

static int average(lua_State *L)
{
    int n = lua_gettop(L);
    double sum = 0;
    int i;

    for (i = 1; i <= n; i++)
    {
            sum += lua_tonumber(L, i);
    }


    lua_pushnumber(L, sum / n);
    lua_pushnumber(L, sum);

    return 2;
}

Use luaL_checktype() , it will return LUA_TTABLE in case of a table. 使用luaL_checktype() ,如果是表,它将返回LUA_TTABLE Then use lua_getfield() or lua_gettable() or lua_rawget() to extract data from the table. 然后使用lua_getfield()lua_gettable()lua_rawget()从表中提取数据。

Edit: 编辑:

To create a new table use lua_newtable() and the fill in the contents with lua_setfield() or lua_rawset[i]() . 要创建新表,请使用lua_newtable()并使用lua_setfield()lua_rawset[i]()填充内容。 Don't forget to leave the table on the stack and return 1. 不要忘记将表格留在堆栈上并返回1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM