简体   繁体   中英

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.

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?

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. Then use lua_getfield() or lua_gettable() or lua_rawget() to extract data from the table.

Edit:

To create a new table use lua_newtable() and the fill in the contents with lua_setfield() or lua_rawset[i]() . Don't forget to leave the table on the stack and return 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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