1

I'm dealing with Lua for a longer time but there is one point I can't achieve. In a C function which is called from Lua I'm able to read a global Lua table using the table name like this:

C:

    // get table
    lua_getglobal(L, "tableName");
    if (!lua_istable(L, -1))                
       break;            

    // count entries in table
    ULONG numEntries = 0; 
    lua_pushnil(L);
    while(lua_next(L,-2))
    {
        numEntries++;
        lua_pop(L, 1);
    }

but if I have a lua function which calls a C function like this:

Lua:

   luaTable = { }
   luaTable.Param1 = Value1 
   luaCallC("This is a Text", luaTable)

How do I access the table argument?

C:

    // get table
    // ???

    // count entries in table
    ULONG numEntries = 0; 
    lua_pushnil(L);
    while(lua_next(L,-2))
    {
        numEntries++;
        lua_pop(L, 1);
    }
1
  • 1
    Its on the stack. Please read the manual as the stack is fundamental to how the C API works. Programming in Lua has usage examples. Commented Oct 19, 2016 at 16:38

1 Answer 1

1

Arguments to a CFunction are pressed onto the virtual stack in the order that they are provided, and it is simply up to you to do the error checking required before you operate on these values.

Lua 5.3 Manual §4.8 - lua_CFunction:

In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first).

[ ... ]

The first argument (if any) is at index 1 and its last argument is at index lua_gettop(L). To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results

An example of exhaustively checking the number of elements in a table, with an arbitrary first argument.

int count (lua_State *L) {
    luaL_checktype(L, 2, LUA_TTABLE);

    puts(lua_tostring(L, 1));
    
    size_t ec = 0;
    
    lua_pushnil(L);
    
    while (lua_next(L, 2)) {
        lua_pop(L, 1);
        ec++;
    }
    
    lua_pushinteger(L, (lua_Integer) ec);
    return 1;
}

After registering the function for use in Lua:

count('foo', { 'a', 'b', 'c' }) -- 3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.