2014-11-02 193 views
1

我真的不確定如何處理Lua C API中的表。 我目前正在開發的接口需要我讀給我的c函數表的 內容:Lua:從c函數調用中讀取表參數

example.lua:

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

C函數我註冊爲 「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; 
} 

我知道有幾種方法可以處理有時需要知道我所做索引的表格。我現在對此感到困惑,而我越研究越多,我就感到困惑。可能是因爲我真的不知道如何用適當的術語來描述我所說的話。

真的很感激,你將如何在間隙填充在我的C函數:)

一些很好的註釋示例代碼(如果你有一個易於理解的指南,這個話題不介意評論)

+2

http://www.lua.org/manual/5.1/manual.html#lua_getfield – 2014-11-02 13:59:01

回答

2
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 
+0

什麼是積極的在lua_getfield的號召代表什麼? 是否就像當c函數調用接收到2個表時,我可以將它遞增1以將第二個表中的值推送到堆棧上? – InDieTasten 2014-11-02 17:06:55

+1

@InDieTasten這是第一個參數(即表)的堆棧索引。 – IllidanS4 2014-11-02 17:10:36