9 class LuaRefWithDeleter {
11 LuaRefWithDeleter(std::mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
12 ~LuaRefWithDeleter() {
13 std::lock_guard<std::mutex> lock(*m);
14 luaL_unref(L, LUA_REGISTRYINDEX, ref);
16 int get() const { return ref; }
19 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
26 template<class T, class... Args>
27 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
29 // Construct the C++ object and put it on the stack.
30 void *mem = lua_newuserdata(L, sizeof(T));
31 new(mem) T(std::forward<Args>(args)...);
33 // Look up the metatable named <class_name>, and set it on the new object.
34 luaL_getmetatable(L, class_name);
35 lua_setmetatable(L, -2);
40 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
41 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
42 // and expected to be destructed by it. The object will be of type T** instead of T*
43 // when exposed to Lua.
45 // Note that we currently leak if you allocate an Effect in this way and never call
46 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
47 // and then release that once add_effect() takes ownership.
48 template<class T, class... Args>
49 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
51 // Construct the pointer ot the C++ object and put it on the stack.
52 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
53 *obj = new T(std::forward<Args>(args)...);
55 // Look up the metatable named <class_name>, and set it on the new object.
56 luaL_getmetatable(L, class_name);
57 lua_setmetatable(L, -2);
63 int wrap_lua_existing_object_nonowned(lua_State* L, const char *class_name, T *ptr)
65 // Construct the pointer ot the C++ object and put it on the stack.
66 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
69 // Look up the metatable named <class_name>, and set it on the new object.
70 luaL_getmetatable(L, class_name);
71 lua_setmetatable(L, -2);
76 #endif // !defined(_LUA_UTILS_H)