2012-06-26 53 views
2

我在C++中整合了Lua,現在我有這個表作爲'類',而對於某些函數,它需要一個'self'參數,實際上它是表。該Lua代碼:C++&Lua,推Lua表作爲參數

a = { 
numb = 5, 

create = function(a) 
    print(a); 
end, 

increment = function(self) 
          --self.numb = 6; 
          print(self.numb); 
end, 

decrement = function(self,i) 
          self.numb = self.numb-i; 
          print(self.numb); 
end 
}; 
b = a; 

以及C++位調用的函數(我已經得到了Lua中使用C運行++)

luaL_openlibs(L); 

luaL_dofile (L,"main.lua"); 

lua_getglobal(L, "a"); 
lua_getfield(L, -1, "increment"); 

string arg = "a"; 

lua_pushliteral(L,"a"); 

lua_pcall(L ,1,0,0); 

printf(" \nI am done with Lua in C++.\n"); 

lua_close(L); 

所以,我怎麼能傳遞self參數,作爲表,進入功能增量?

任何幫助表示讚賞

+1

你問的如何在C++中創建一個lua表並將它傳遞給函數? http://stackoverflow.com/questions/453769/how-do-i-create-a-lua-table-in-c-and-pass-it-to-a-lua-function –

+1

這是Lua,而不是LUA或lua ... – 0xC0000022L

+0

不,我想從我的腳本中傳遞一個Lua表,作爲lua函數中的一個參數,我想調用一個C++函數。所以實際上它是一種指向表本身的指針 – dirkwillem

回答

1

在Lua中5.1使用lua_getglobal,恩,獲得了全球性的,就像你的表a - 您使用它來獲取上述短短几行的表;所有你需要做的就是複製該值,將它傳遞給你的函數

lua_getglobal(L, "a"); // the table a is now on the stack 
lua_getfield(L, -1, "increment"); // followed by the value of a.increment 

lua_pushvalue(L,-2); // get the table a as the argument 

lua_pcall(L,1,0,0); 
+0

相同的代碼在Lua 5.2中工作。 – lhf

+0

謝謝,這工作! – dirkwillem

+0

@dirkwillem點擊正確答案旁邊的複選框。沒有必要把[解決]放在問題標題中。 –