2

I'm messing around with variadic templates and trying to workout a luabinding scheme going. I know they exist but just trying to mess around with new features. I'm working is a VS2013 trial currently. I've created a functor class that is a wrapper around the information I need to call a lua function from the C++ side; However, I can't for the life of me get my template function that is made to push the variables onto the stack to unpack and work. I've tried every example on the net I could find and tried every way they mention how to unpack the values for function templates. I'm obviously missing something. All the examples I noticed took && move references. Is that a requirement?

/*
These functions push an item onto the lua stack
*/
template<typename T> inline void lua_push(lua_State* L,T&& t){ static_assert(false,      "Unsupported Type! Cannot set to lua stack"); }
template<> inline void lua_push<lua_CFunction>(lua_State* L,lua_CFunction&& func){      assert(L != nullptr && func != nullptr); lua_pushcfunction(L, func); }
template<> inline void lua_push<double>(lua_State* L,double&& d){ assert(L != nullptr);  lua_pushnumber(L, d); }
template<> inline void lua_push<int>(lua_State* L,int&& i){ assert(L != nullptr);  lua_pushinteger(L, i); }
template<> inline void lua_push<bool>(lua_State* L,bool&& b){ assert(L != nullptr);  lua_pushboolean(L, b); }
template<> inline void lua_push<std::string>(lua_State* L,std::string&& s){ assert(L != nullptr);  lua_pushlstring(L, s.c_str(), s.size()); }
template<> inline void lua_push<const char*>(lua_State* L,const char*&& s){ assert(L != nullptr); lua_pushstring(L, s); }

Then I want to unpack it in this class

template<typename Return,typename... Args> class LuaFunctor{};
/*
    A Lua function that will return a single value.
*/
template<typename Return,typename... Args> class LuaFunctor<Return(Args...)>
{
private:
    //The lua state the function exists on
    lua_State* m_luaState;
    //Name of the function to be called in lua
    std::string m_FunctionName;
public:
    //Return typedef
    typedef Return return_type;
    //The number of arguments the functor accepts
    static const int arguments = sizeof...(Args);
    //Constructors
    inline LuaFunctor(lua_State* L,const std::string& name) : m_luaState(L), m_FunctionName(name) {}
    inline LuaFunctor(lua_State* L,const char* name) : m_luaState(L), m_FunctionName(name) {}
    //Function call overload that allows the functor to act like a function call of luascript
    inline Return operator()(Args&&... args)
    {
        //Assert that the function name does exist and luaState is pointing to something hopefully meaningful
        assert(m_luaState != nullptr && m_FunctionName.size() != 0);
        //Set the function
        lua_getglobal(m_luaState, m_FunctionName.c_str());
        //Verify Lua function is pushed onto the stack
        assert(lua_isfunction(m_luaState, -1));
        //If arguments exist push them onto the stack
        if (sizeof...(Args) != 0)
        {
                    /*
                      How do I unpack this?????
                      I want to unpack this into multiple functions
                      One for each type of argument.
                    */
            lua_push(m_luaState, std::forward<Args>(args))...; 
        }
        //Call the function that is in lua
        int status = lua_pcall(m_luaState, sizeof...(Args), 1, 0);
        /*
            If there was an error calling the function throw an exception
            TODO: parse the error using luas builtin decode of the error for now just pass it on
            TODO: create lua_exception
        */
        if (status != 0) throw std::exception("Error calling lua function");
        //Return the value request by lua, error checking is built-in to the function to verify type
        return lua_get<Return>(m_luaState);
    }
};
6
  • Can you add what happens with your above code? Does it compile successfully? Are you sure lua_push's inside if (sizeof...(Args) != 0) is getting called?
    – greatwolf
    Oct 28, 2013 at 12:35
  • No it wasn't compiling. I found a solution though. template<typename First, typename... Rest> inline void lua_push(lua_State* L,First first,Rest... rest) { lua_push(L, first); lua_push(L, rest...); } this function recursively calls lua_push grabbing the correct type each time. Then I just need to call lua_push(L,args...); and no headache. Oct 28, 2013 at 12:47
  • 3
  • what you are calling move references is actually perfect forwarding and universal references in that context: related but not the quite the same. If you want tonunderstand what they do, google those terms. Oct 29, 2013 at 1:06
  • @xeo order issues there? I forget. Oct 29, 2013 at 1:10

2 Answers 2

4

Here is the fix. Recursive function calls. Tried all sorts of hacks that I was reading about but this is clean and simple.

/*
    These functions push an item onto the lua stack
*/
template<typename First, typename... Rest> inline void lua_push(lua_State* L,First first,Rest... rest)
{
    lua_push(L, first);
    lua_push(L, rest...);
}
template<typename T> inline void lua_push(lua_State* L, T t){ static_assert(false, "Invalid type attemptiing to be pushed onto lua stack!"); }
template<> inline void lua_push<lua_CFunction>(lua_State* L, lua_CFunction func){ assert(L != nullptr && func != nullptr); lua_pushcfunction(L, func); }
template<> inline void lua_push<double>(lua_State* L, double d){assert(L != nullptr);  lua_pushnumber(L, d); }
template<> inline void lua_push<int>(lua_State* L, int i){ assert(L != nullptr);  lua_pushinteger(L, i); }
template<> inline void lua_push<bool>(lua_State* L, bool b){ assert(L != nullptr);  lua_pushboolean(L, b); }
template<> inline void lua_push<std::string>(lua_State* L, std::string s){assert(L != nullptr);  lua_pushlstring(L, s.c_str(), s.size()); }
template<> inline void lua_push<const char*>(lua_State* L,const char* s){ assert(L != nullptr); lua_pushstring(L, s); }

The code works perfectly now.

template<typename Return,typename... Args> class LuaFunctor<Return(Args...)>
{
private:
    //The lua state the function exists on
    lua_State* m_luaState;
    //Name of the function to be called in lua
    std::string m_FunctionName;
public:
    //Return typedef
    typedef Return return_type;
    //The number of arguments the functor accepts
    static const int arguments = sizeof...(Args);
    //Constructors
    inline LuaFunctor(lua_State* L,const std::string& name) : m_luaState(L), m_FunctionName(name) {}
    inline LuaFunctor(lua_State* L,const char* name) : m_luaState(L), m_FunctionName(name) {}
    //Function call overload that allows the functor to act like a function call of luascript
    inline Return operator()(Args... args)
    {
        //Assert that the function name does exist and luaState is pointing to something hopefully meaningful
        assert(m_luaState != nullptr && m_FunctionName.size() != 0);
        //Set the function
        lua_getglobal(m_luaState, m_FunctionName.c_str());
        //Verify Lua function is pushed onto the stack
        assert(lua_isfunction(m_luaState, -1));
        //If arguments exist push them onto the stack
        if (sizeof...(Args) != 0) lua_push(m_luaState, args...);
        //Call the function that is in lua
        int status = lua_pcall(m_luaState, sizeof...(Args), 1, 0);
        /*
            If there was an error calling the function throw an exception
            TODO: parse the error using luas builtin decode of the error for now just pass it on
            TODO: create lua_exception
        */
        if (status != 0)
        {
            report_errors(status);
            throw std::exception("Error calling lua function");
        }
        //Return the value request by lua, error checking is built-in to the function to verify type
        return lua_get<Return>(m_luaState);
    }
};
2
  • You may remove template<typename T> inline void lua_push(lua_State* L, T t), and use simple non template functions inline void lua_push(lua_State* L, lua_CFunction func) {/*implementation*/}. assert(m_luaState != nullptr && m_FunctionName.size() != 0); may be moved in constructor... Your inline within the class are superfluous.
    – Jarod42
    Oct 28, 2013 at 13:31
  • Yeah, code could be cleaned a bit and it isn't finished. The assert in the () operator is eventually going to be calling other things and have a smart_prt check for the lua_State, so it's more a place holder then anything for more advanced debug checks. Could get rid of the inlines for sure though. Oct 29, 2013 at 1:22
1

The easiest would be to change lua_push into a bunch of overrides.

Have them return some copy or movable type (bool will do, or struct nothing{};).

Then:

auto sink[]={lua_push(m_luaState, std::forward<Args>(args))...};

which calls them all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.