[11519] | 1 | |
---|
| 2 | #include <lua.hpp> |
---|
| 3 | #include <iostream> |
---|
| 4 | #include <type_traits> |
---|
| 5 | #include "scriptable_controller_api.h" |
---|
| 6 | #include "luatb_typed_stack.h" |
---|
| 7 | |
---|
| 8 | |
---|
| 9 | // TODO Make free functions work |
---|
| 10 | |
---|
| 11 | // This class is only valid for function types. As a neat side-effect, having |
---|
| 12 | // this specialization in the .ipp file, also hides all of the private members |
---|
| 13 | // from the user (kind of). |
---|
| 14 | template<typename ThisType, typename Ret, typename... Args> |
---|
| 15 | class LuaTB<ThisType, Ret (ThisType::*)(Args...)> |
---|
| 16 | { |
---|
| 17 | public: |
---|
| 18 | template<Ret (ThisType::*func)(Args...)> |
---|
| 19 | static void registerFunction(ThisType *_this, lua_State *lua, std::string name) |
---|
| 20 | { |
---|
| 21 | // Store the 'this' pointer of the caller in the extraspace |
---|
| 22 | // *static_cast<ThisType**>(lua_getextraspace(lua)) = _this; |
---|
| 23 | |
---|
| 24 | // Make a function visible to lua that will call 'func' with the correct |
---|
| 25 | // arguments |
---|
| 26 | lua_register(lua, name.c_str(), toLuaSignature<func>); |
---|
| 27 | } |
---|
| 28 | |
---|
| 29 | private: |
---|
| 30 | // Represents a function that can made visible to lua with the correct |
---|
| 31 | // signature. It will call the corresponding C++ function with the |
---|
| 32 | // correctly typed arguments |
---|
| 33 | template<Ret (ThisType::*func)(Args...)> |
---|
| 34 | static int toLuaSignature(lua_State *lua) |
---|
| 35 | { |
---|
| 36 | // The number of arguments is the first item on the stack |
---|
| 37 | int argc = lua_tointeger(lua, lua_gettop(lua)); |
---|
| 38 | lua_pop(lua, 1); |
---|
| 39 | |
---|
| 40 | // Check if the number of arguments match |
---|
| 41 | if(argc != sizeof...(Args)) |
---|
| 42 | { |
---|
| 43 | std::cerr << "ERROR: LuaTB: Lua script called a function with wrong number of arguments" << std::endl; |
---|
| 44 | return LUA_ERRSYNTAX; |
---|
| 45 | } |
---|
| 46 | |
---|
| 47 | // Retrieve 'this' pointer of caller |
---|
| 48 | // ThisType *_this = *static_cast<ThisType**>(lua_getextraspace(lua)); |
---|
| 49 | ThisType *_this = orxonox::ScriptableControllerAPI::this_; |
---|
| 50 | |
---|
| 51 | // Call getArgument for every argument seperately to convert each argument |
---|
| 52 | // to the correct type and call the function afterwards |
---|
| 53 | ((*_this).*func)( (LuaTBTypedStack::getArgument<Args>(lua))... ); |
---|
| 54 | |
---|
| 55 | return 0; |
---|
| 56 | } |
---|
| 57 | }; |
---|