【发布时间】:2020-08-17 02:59:07
【问题描述】:
我正在尝试制作一个非常简单的 lua 包装器,可用于加载和运行多个 Lua 脚本。我很担心,因为我没有看到任何关于如何在不完全破坏 lua_State 本身的情况下正确销毁/删除加载的脚本的文档。
是否可以删除/卸载加载的 lua 脚本?这是不必要的还是会不断调用 luaL_dofile 导致内存泄漏?
简化问题....如果我在同一个 lua_State 对象上调用 luaL_dofile,这会导致内存泄漏或问题,还是 lua 在加载新脚本时会在后端处理这个问题?
这是一个演示......
lua_State* m_lua_state = luaL_newstate();
lua_gc(m_lua_state, LUA_GCSTOP, 0);
luaL_openlibs(m_lua_state);
lua_gc(m_lua_state, LUA_GCRESTART, 0);
for(int i = 0; i < 99999999; i++)
{
// Since I don't unload the previous file, does this cause a memory leak until lua_close is called?
if (luaL_dofile(m_lua_state, file_path.c_str()) != LUA_OK)
{
std::string error_msg = lua_tostring(m_lua_state, -1);
std::cout << "Error: " << error_msg << std::endl;
return false;
}
else
{
lua_getglobal(m_lua_state, function_name.c_str());
if (lua_isfunction(m_lua_state, -1))
{
int stack_size = lua_gettop(m_lua_state);
int number_of_args = 0;
if (lua_pcall(m_lua_state, number_of_args, 0, 0) != LUA_OK)
{
std::cout << "Error Calling Function In Script: " << file_path << "::" << function_name << " - " << lua_tostring(m_lua_state, -1) << std::endl;
}
int total_return_values = lua_gettop(m_lua_state) - stack_size;
}
else
{
std::cout << "Error Invalid Function In Script: " << file_path << "::" << function_name << std::endl;
}
}
}
lua_close(m_lua_state);
【问题讨论】:
-
如果脚本只定义了一个函数,则无需“卸载”脚本。多次重新定义全局函数不会泄漏内存。之前的函数将在最近的 GC 事件中收集。但是函数本身(在执行时)会吃掉内存。