C++调用Lua函数



我即将在我的项目中包含Lua。只有一个问题,如果我链接我自己的类并在Lua中创建它,堆栈就不会被清理,我会出现内存泄漏。记忆越来越高。

MyClass:

class CTest
{
public:
CTest(std::string s)
: m_s(s)
{
std::cout << s << std::endl;
}
~CTest()
{
}
private:
std::string m_s;
};

C++测试代码:

auto state = luaL_newstate();
luaL_openlibs(state);
luabridge::getGlobalNamespace(state)
.beginClass<CTest>("Test")
.addConstructor<void(*)(std::string)>()
.endClass();
int iState = luaL_dofile(state, "Test.lua");
while (true)
{
int nStatus = 0;
lua_getglobal(state, "test");
nStatus = lua_pcall(state, 0,0,0);
}

Lua代码

local ii = 0
function test()
local i = Test("Hallo " .. ii)
ii = ii + 1
end

我使用的是Lua 5.2.0。

我可以在Lua 5.2.0上复制您的问题,但不能在Lua 5.2.1或任何更新版本上复制。我的结论是,这只是Lua 5.2.1之前版本中的一个bug。只要更新到Lua的现代版本,你也不应该有这个问题。

最新更新