简体   繁体   中英

Call Lua Function From A Global Table In C++

I've defined some Lua functions in a global Hooks table as follows:

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")

Users can then add their own functions into the hook system with unique identifiers then remove them if needed.

I need to figure out how to call the Hooks.Call() function from within C++ but I only know how to call global functions, not functions within tables which are in the global scope. A way to do what Hooks.Call() is doing completely in C++ would be the most efficient route.

This allowed me to call the Lua function from C++

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;
}

Is this code complete? Is the stack clear at this point?

Your code looks alright to me.

  • You've left the Hooks table on the stack. You can remove it right after the call to lua_getfield . Alternatively, encapsulate a "table.field" retrieval in a utility function. Ie something along of getglobal2(m_Lua, "Hooks", "Call") .

  • You're also leaving the error message on the stack. You need to pop it.

Alternatively, wrap your code in a Lua function (written on the C side) and call it via lua_pushcfunction & lua_pcall . This way the stack will be automatically managed for you.

BTW, you can do v(...) instead of v(unpack(arg)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM