InDieTasten
InDieTasten

Reputation: 2471

Lua: Read table parameter from c function call

I'm really unsure about handling tables in the C API of Lua. The interface I'm currently developing requires me to read contents of a table given to my c function:

example.lua:

myVector2 = {["x"]=20, ["y"]=30}
setSomePosition(myVector2)

C function I register as "setSomePosition":

static int lSetSomePosition(lua_State *L)
{
    //number of arguments
    if(lua_gettop(L) != 1)
    {
        //error handling
        return 0;
    }
    //Need your help with the following:
    //extract tables values of indexes "x" and "y"

    return 0;
}

I know there are a couple of ways handling tables of which you sometimes need to know the indexes which I do. I'm just confused right now about this and the more I research the more I get confused. Probably because I don't really know how to describe what I'm after in proper terminology.

Would really appreciate some good commented example code of how you would fill in the gap in my c function :)

(If you've got an easy to understand guide to this topic don't mind commenting)

Upvotes: 1

Views: 803

Answers (1)

IS4
IS4

Reputation: 13177

lua_getfield(L, 1, "x") //pushes a value of t["x"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack
lua_getfield(L, 1, "y") //pushes a value of t["y"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack

Upvotes: 2

Related Questions