2013-01-08 29 views
2

在Lua代碼
山口純LUA對象的C函數,並獲得價值

Test = {} 
function Test:new() 
    local obj = {} 
    setmetatable(obj, self) 
    self.__index = self 
    return obj 
end 
local a = Test:new() 
a.ID = "abc123" 
callCfunc(a) 

C代碼

int callCfunc(lua_State * l) 
{ 
    void* obj = lua_topointer(l, 1);   //I hope get lua's a variable 
    lua_pushlightuserdata(l, obj); 
    lua_getfield(l, 1, "ID"); 
    std::string id = lua_tostring(l, 1);  //I hoe get the value "abc123" 
    ... 
    return 0; 
} 

但我的C測試結果爲

id = null 

爲什麼?如何修改代碼工作正常?
PS:我不希望創建C測試類映射到Lua

==== ==== UPDATE1
此外,我已經添加了測試代碼,確認無誤傳入的參數。

int callCfunc(lua_State * l) 
{ 
    std::string typeName = lua_typename(l, lua_type(l, 1)); // the typeName=="table" 
    void* obj = lua_topointer(l, 1);   //I hope get lua's a variable 
    lua_pushlightuserdata(l, obj); 
    lua_getfield(l, 1, "ID"); 
    std::string id = lua_tostring(l, 1);  //I hoe get the value "abc123" 
    ... 
    return 0; 
} 

結果

typeName == "table" 

所以傳入的參數類型是正確的

+2

不完全的C代碼。 – chris

+0

不是從0索引的對象嗎?不是所有的1都是零? – 2013-01-08 05:55:11

+0

您可能想接受一些答案 - 您會得到更多回復。 0%接受小於可接受:-) – daven11

回答

2

頂部我找到了原因
正確的C代碼應該是...
C代碼

int callCfunc(lua_State * l) 
{ 
    lua_getfield(l, 1, "ID"); 
    std::string id = lua_tostring(l, -1);  //-1 
    ... 
    return 0; 
} 
+0

如何關閉該問題?我沒有找到關閉菜單。 – Flash

+0

使用lua_istable()檢查輸入參數是否爲表格 - http://pgl.yoyo.org/luai/i/lua_istable。要結束這個問題只是接受一個答案 - 如果你的話,那麼你將不得不等待一段時間我想。 – daven11

0

也許這 - 沒有測試過遺憾 - 沒有編譯器方便

輸入是表從lua頂部的堆棧中,所以getfield(l,1,「ID」)應該從堆棧頂部的表中獲得字段ID - 在本例中是您的輸入表。然後,它推動的結果到堆棧

int callCfunc(lua_State * l) 
{ 
    lua_getfield(l, 1, "ID"); 
    std::string id = lua_tostring(l, 1);  //I hoe get the value "abc123" 
    ... 
    return 0; 
} 
+0

我測試了你的修改代碼。它仍然是錯誤的。 ID = null – Flash