我想使用LUAPlus將Lua表函數鏈接到C++變量。到目前爲止,使用我可以在網上找到的信息,我設法使用DoString("tableName:functionName")
來調用表函數,但是我希望能夠通過變量調用函數。我知道它是可能的,但我不知道我做錯了什麼。使用LUAPlus將Lua表函數綁定到C++變量
在我添加的代碼中,pLuaState->DoString("table1:prints()")
工作正常,並根據需要打印所有內容。 0,文件.../luafunciton.h 41行: 當我試圖讓功能和使用FUNC變量調用它,我的程序與
錯誤信息
斷言失敗崩潰
如果我在Lua的prints()函數中除了「print(」在「prints」)中刪除了所有的打印件,一切正常。基於此,我假設GetByName("functionName")
返回一個函數,該函數不包含對其父表的引用。這就是我陷入困境的地方。
的main.cpp
pLuaState = LuaPlus::LuaState::Create(true);
pLuaState->DoFile("test.lua");
LuaObject globals = pLuaState->GetGlobals();
LuaObject metaTableObj = pLuaState->GetGlobals().Lookup("RandomMove");
if (metaTableObj.IsNil())
{
metaTableObj = pLuaState->GetGlobals().CreateTable("RandomMove");
}
metaTableObj.SetObject("__index", metaTableObj);
metaTableObj.RegisterObjectDirect("GetX", (TestLua*)0, &TestLua::GetX);
metaTableObj.RegisterObjectDirect("SetX", (TestLua*)0, &TestLua::SetX);
TestLua obj1(6);
LuaObject table1Obj = pLuaState->GetGlobals().CreateTable("table1");
table1Obj.SetLightUserData("__object", &obj1);
table1Obj.SetObject("__index", metaTableObj);
table1Obj.SetMetaTable(metaTableObj);
pLuaState->DoString("table1:prints()");
auto prints = table1Obj.GetByName("prints");
if (!prints.IsFunction())
cout << "nil function" << endl;
else
{
LuaPlus::LuaFunction<void> func(prints);
func();
}
test.lua
print("test.lua")
RandomMove =
{
_thing = 1
}
function RandomMove:SetThing()
print("I am "..tostring(self.__object))
end
function RandomMove:prints()
print("in prints")
print("__object is: " .. tostring(self.__object))
print("_thing is: ".. tostring(self._thing))
print(self:GetX())
end
任何幫助,將不勝感激。
謝謝!所以它就像C++中的「this」參數 – inzombiak
「automagic」參數非常類似於'this',是的,lua使用'self'作爲lua代碼中的變量名來實現這樣的功能。 –