c++c++11luameta-method

Calling Lua Functions From C++


I'm using the latest version of LuaJit and need some help getting started. What I need is to have a bunch of functions exposed to the Lua environment which can be overridden inside the scripts to run the user's supplied code, these functions would then be called during set events from within C++

For example, when the user presses their TAB key down it would call a function from the lua environment such as OnScoreboardOpen() and when the user releases their TAB key it would call the corresponding function OnScoreboardClose() these functions could be attached to a metamethod like Game or GM.

Could someone point me to some tutorials or sample code showing how this can be accomplished? Thank you very much for your time.


Solution

  • Basically you use these two functions: lua_pushXXX and lua_pcall

    Depends on how you name the LUA function, it can be plain function or object method. i.e.

    function OnScoreboardOpen()
    end
    

    OR

    function Game:OnScoreboardOpen()
    end
    

    It's relatively simple to use plain function, just do:

    // TODO: sanity check
    lua_getglobal(L, name);
    lua_pushnumber(L,123);
    lua_pcall(...);