2012-05-29 46 views
0

我要讓這樣的工作:
1.創建對象在Lua
2.獲取該對象到C++
3.此對象從C++
在C++ LUA對象

通過它執行一些方法

現在我有這個在Lua:

Account = {balance = 0} 

function Account.Create(name) 
    local a = Account:new(nil, name); 
    return a; 
end 

function Account:new (o, name) 
    o = o or {name=name} 
    setmetatable(o, self) 
    self.__index = self 
    return o 
end 

function Account:Info() 
    return self.name; 
end 

代碼在C++

//get Lua object 

lua_getglobal (L, "Account"); 
lua_pushstring(L, "Create"); 
lua_gettable(L, -2); 
lua_pushstring(L, "SomeName"); 
lua_pcall(L, 1, 1, 0); 
const void* pointer = lua_topointer(L, -1); 
lua_pop(L, 3); 

//then I want to perform some method on object 

lua_getglobal (L, "Account"); 
lua_pushstring(L, "Info"); 
lua_gettable(L, -2); 
lua_pushlightuserdata(L,(void*) pointer); 
lua_pcall(L, 0, 1, 0); 
//NOW I GET "attempt to index local 'self' (a userdata value)' 
const char* str = lua_tostring(L, -1); 
...etc... 

你我做錯了什麼?我怎樣才能得到這個Lua對象到C++?

回答

2
const void* pointer = lua_topointer(L, -1); 

Lua表不是C對象。他們不是void* s。 lua_topointer documentation表示該函數主要用於調試目的。你沒有調試任何東西。

只能通過Lua API訪問Lua表。你不能只是得到一個指向一個Lua表或其他東西的指針。相反,你需要做的是將Lua表存儲在一個地方,然後當你想要訪問它時,從那個位置檢索它。存儲這類數據的典型地方是Lua註冊表。從Lua代碼無法訪問;只有C-API可以與之通話。

通常,您將在註冊表中存儲一些表,其中包含您當前擁有的所有Lua值。這樣,您使用註冊表不會使別人使用它。