我在全局Hooks
表中定义了一些 Lua 函数,如下所示:
print("Loading Hook System")
local pairs = pairs;
Hooks = {}
Hooks.Hooks = {}
----------
-- This file defines all the available hooks
----------
Hooks.Hooks.OnScoreboardOpen = {}
function Hooks.Add( Name, Identifier, Function )
if (Hooks.Hooks[Name] == nil) then
print("Hook "..Name.." Does Not Exist")
else
if (Hooks.Hooks[Name][Identifier] == nil) then
Hooks.Hooks[Name][Identifier] = Function
else
print("Hooks.Add Error: Identifier: "..Identifier.." Already Exists")
end
end
end
function Hooks.Remove( Identifier )
for _,Hook in pairs(Hooks.Hooks) do
if (Hook[Identifier]) then
Hook[Identifier] = nil
end
end
end
function Hooks.Call( Name, ... )
local arg = {...}
for _,v in pairs(Hooks.Hooks[Name]) do
v(unpack(arg))
end
end
print("Complete")
然后,用户可以使用唯一标识符将自己的函数添加到 Hook 系统中,然后在需要时将其删除。
我需要弄清楚如何从 C++ 中调用 Hooks.Call()
函数,但我只知道如何调用全局函数,而不是全局范围内的表中的函数。完全在 C++ 中执行 Hooks.Call()
操作的方法将是最有效的途径。
这让我可以从 C++ 调用 Lua 函数
lua_getglobal(m_Lua, "Hooks");
lua_getfield(m_Lua, -1, "Call");
lua_pushstring(m_Lua, "OnScoreboardOpen");
lua_pushnumber(m_Lua, 5);
lua_pushnumber(m_Lua, 7);
int Error = lua_pcall(m_Lua, 3, 0, 0);
if (Error)
{
std::cout << lua_tostring(m_Lua, -1) << std::endl;
}
这段代码完整吗?此时堆栈是否清除?
最佳答案
我觉得你的代码没问题。
您已将
Hooks
表留在堆栈中。您可以在调用lua_getfield
后立即删除它。或者,将“table.field”检索封装在实用程序函数中。 IE。getglobal2(m_Lua, "Hooks", "Call")
的一些东西。您还将错误消息留在堆栈上。你需要弹出它。
或者,将您的代码包装在一个 Lua 函数中(在 C 端编写)并通过 lua_pushcfunction
和 lua_pcall
调用它。这样,堆栈将自动为您管理。
顺便说一句,你可以用v(...)
代替v(unpack(arg))
。
关于c++ - 从 C++ 中的全局表调用 Lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856691/