1
votes

I started using C++ dll with lua together. It's very hard to start. I need help to work with tables. I do the following in my C++ code:

static int forLua_AddTwoNumbers(lua_State *L) {
    double d1 = luaL_checknumber(L, 1);
    double d2 = luaL_checknumber(L, 2);
    lua_pushnumber(L, d1 + d2);
    return(1); 
}

and call this function in lua:

r = runfast.AddTwoNumbers(2, 5)

It works. How can I do the same with a table like this:

lua table t={1=20, 2=30, 3=40}
1
Have you read the documentation? What did you try? What errors did you encounter? - Alan Birtles

1 Answers

0
votes

I'm assuming that you're asking how to add up all the values in an array?

static int forLua_SumArray (lua_State* L) {
    // Get the length of the table (same as # operator in Lua)
    int n = luaL_len(L, 1);
    double sum = 0.0;

    // For each index from 1 to n, get the table value as a number and add to sum
    for (int i = 1; i <= n; ++i) {
      lua_rawgeti(L, 1, i);
      sum += lua_tonumber(L, -1);
      lua_pop(L, 1);
    }

    lua_pushnumber(L, sum);
    return 1; 
}

By the way, in Lua, t={1=20, 2=30, 3=40} can be written more simply as t={20, 30, 40}. This is how one typically writes arrays.

You might also want to take a look at the manual's example code for summing a variable number of arguments. Almost the same as what we're doing here, except you might prefer passing multiple arguments instead of having to use a table.