Created
March 28, 2017 01:09
-
-
Save djarek/3acbaa156fa217fc835f83ed246f04a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <lua.h> | |
#include <type_traits> | |
template<typename LuaPushable> | |
void LuaPush(lua_State& state, LuaPushable&& luaPushable); | |
template <> | |
void LuaPush(lua_State& state, const std::string& str) | |
{ | |
lua_pushlstring(&state, str.c_str(), str.length()); | |
} | |
template <> | |
void LuaPush(lua_State& state, std::string&& str) | |
{ | |
lua_pushlstring(&state, str.c_str(), str.length()); | |
} | |
template <typename... LuaPushables> | |
void LuaPush(lua_State& state, LuaPushables&&... luaPushables) | |
{ | |
LuaPush(state, std::forward<LuaPushables&&>(luaPushables)...); | |
} | |
template <typename Integer, typename ReturnType> | |
using EnableIfInteger = typename std::enable_if<std::is_integral<Integer>::value, ReturnType>::type; | |
template<typename FloatingNumber, typename ReturnType> | |
using EnableIfFloatingPoint = typename std::enable_if<std::is_floating_point<FloatingNumber>::value, void>::type; | |
template <typename Integer> | |
EnableIfInteger<Integer, void> LuaPush(lua_State& state, Integer integer) | |
{ | |
lua_pushinteger(&state, integer); | |
} | |
template<typename FloatingNumber> | |
EnableIfFloatingPoint<FloatingNumber, void> LuaPush(lua_State& state, FloatingNumber number) | |
{ | |
lua_pushnumber(&state, number); | |
} | |
template<typename T> | |
class LuaFunction; | |
template<typename Result, typename... ArgumentTypes> | |
class LuaFunction<Result(ArgumentTypes...)> | |
{ | |
public: | |
constexpr LuaFunction() noexcept = default; | |
explicit LuaFunction(lua_State& state): | |
state(&state) {} | |
Result operator()(ArgumentTypes&&... luaObjects) const | |
{ | |
LuaPush(*state, std::forward<ArgumentTypes&&>(luaObjects)...); | |
}; | |
private: | |
lua_State* state = nullptr; | |
int luaFunctionRef = -1; | |
}; | |
void test(lua_State& L) | |
{ | |
LuaFunction<void(std::string, int, double)> func{L}; | |
func(std::string{"foo"}, 1, 1.2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment