LPCGame
A Simple 2d Game Engine
 All Classes Namespaces Functions Variables Enumerations Enumerator Pages
luacprimitiveparam.h
1 #ifndef LUAPRIMITIVEPARAM_H
2 #define LUAPRIMITIVEPARAM_H
3 
4 #include <functional>
5 #include <string>
6 #include <lua.hpp>
7 
9 
13 namespace LuaC {
14  template<class T>
15  class LuaPrimitiveParam : public LuaParam {
16  public:
21  LuaPrimitiveParam(T obj) : mObj(obj) {}
26  void Push(lua_State *l) override {
27  mPusher(l, mObj);
28  }
34  void Push(lua_State *l, std::string name) override {
35  Push(l);
36  lua_setglobal(l, name.c_str());
37  }
43  static T Retrieve(lua_State *l) {
44  return mRetriever(l, -1);
45  }
46 
47  private:
48  const T mObj;
49  const static std::function<void(lua_State*, T)> mPusher;
50  const static std::function<T(lua_State*, int)> mRetriever;
51  };
52  //Pusher function specializations
53  //Bool
54  typedef LuaPrimitiveParam<bool> BoolParam;
55  template<>
56  const std::function<void(lua_State*, bool)> BoolParam::mPusher = lua_pushboolean;
57  //We need to use this in-between lambda for now due to compiler issues
58  const static auto bRetrieve = [](lua_State *l, int idx){ return lua_toboolean(l, idx) == 1; };
59  template<>
60  const std::function<bool(lua_State*, int)> BoolParam::mRetriever = bRetrieve;
61 
62  //Double
63  typedef LuaPrimitiveParam<double> DoubleParam;
64  template<>
65  const std::function<void(lua_State*, double)> DoubleParam::mPusher = lua_pushnumber;
66  template<>
67  const std::function<double(lua_State*, int)> DoubleParam::mRetriever = luaL_checknumber;
68 
69  //Float
70  typedef LuaPrimitiveParam<float> FloatParam;
71  template<>
72  const std::function<void(lua_State*, float)> FloatParam::mPusher = lua_pushnumber;
73  template<>
74  const std::function<float(lua_State*, int)> FloatParam::mRetriever = luaL_checknumber;
75 
76  //Int
77  typedef LuaPrimitiveParam<int> IntParam;
78  template<>
79  const std::function<void(lua_State*, int)> IntParam::mPusher = lua_pushinteger;
80  template<>
81  const std::function<int(lua_State*, int)> IntParam::mRetriever = luaL_checkinteger;
82 
83  //String (a lambda function is used b/c lua_pushstring takes a char* not a std::string)
84  typedef LuaPrimitiveParam<std::string> StringParam;
85  //We need to use this in-between lambda for now due to compiler issues
86  const static auto sPusher = [](lua_State *l, std::string str){ return lua_pushstring(l, str.c_str()); };
87  template<>
88  const std::function<void(lua_State*, std::string)> StringParam::mPusher = sPusher;
89  //We need to use this in-between lambda for now due to compiler issues
90  const static auto sRetriever = [](lua_State *l, int i){ return (std::string)luaL_checkstring(l, i); };
91  template<>
92  const std::function<std::string(lua_State*, int)> StringParam::mRetriever = sRetriever;
93 
94 }
95 #endif