Pioneer
LuaRef.h
Go to the documentation of this file.
1 // Copyright © 2008-2023 Pioneer Developers. See AUTHORS.txt for details
2 // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
3 
4 #ifndef _LUAREF_H
5 #define _LUAREF_H
6 
7 #include "JsonFwd.h"
8 #include <cassert>
9 #include <lua.hpp>
10 #include <vector>
11 
12 class LuaRef {
13 public:
14  LuaRef() :
15  m_lua(0),
16  m_id(LUA_NOREF),
17  m_copycount(nullptr) {}
18  LuaRef(lua_State *l, int index);
19  LuaRef(const LuaRef &ref);
20  ~LuaRef();
21  const LuaRef &operator=(const LuaRef &ref);
22  bool operator==(const LuaRef &ref) const;
23 
24  void PushCopyToStack() const;
25 
26  lua_State *GetLua() const { return m_lua; }
27 
28  bool IsValid() const { return m_lua && m_id != LUA_NOREF; }
29  bool IsNil() const { return m_lua && m_id == LUA_REFNIL; }
30 
31  void SaveToJson(Json &jsonObj);
32  void LoadFromJson(const Json &jsonObj);
33  void Unref();
34 
35 private:
36  lua_State *m_lua;
37  int m_id;
38  int *m_copycount;
39 
40  // Does everything we need: get the table, or create it if it doesn't exist.
41  // Yay lua aux lib !
42  void PushGlobalToStack() const { luaL_getsubtable(m_lua, LUA_REGISTRYINDEX, "LuaRef"); }
43 
44  void CheckCopyCount();
45 };
46 
47 inline void pi_lua_generic_push(lua_State *l, const LuaRef &r)
48 {
49  assert(r.GetLua() == l);
50  r.PushCopyToStack();
51 }
52 
53 inline void pi_lua_generic_pull(lua_State *l, int index, LuaRef &r)
54 {
55  r = LuaRef(l, index);
56 }
57 
58 inline bool pi_lua_strict_pull(lua_State *l, int index, LuaRef &r)
59 {
60  r = LuaRef(l, index);
61  return true;
62 }
63 
64 #endif
nlohmann::json Json
Definition: Json.h:8
bool pi_lua_strict_pull(lua_State *l, int index, LuaRef &r)
Definition: LuaRef.h:58
void pi_lua_generic_push(lua_State *l, const LuaRef &r)
Definition: LuaRef.h:47
void pi_lua_generic_pull(lua_State *l, int index, LuaRef &r)
Definition: LuaRef.h:53
Definition: LuaRef.h:12
void SaveToJson(Json &jsonObj)
Definition: LuaRef.cpp:97
bool IsNil() const
Definition: LuaRef.h:29
LuaRef()
Definition: LuaRef.h:14
bool IsValid() const
Definition: LuaRef.h:28
const LuaRef & operator=(const LuaRef &ref)
Definition: LuaRef.cpp:20
~LuaRef()
Definition: LuaRef.cpp:34
bool operator==(const LuaRef &ref) const
Definition: LuaRef.cpp:47
void PushCopyToStack() const
Definition: LuaRef.cpp:89
lua_State * GetLua() const
Definition: LuaRef.h:26
void LoadFromJson(const Json &jsonObj)
Definition: LuaRef.cpp:121
void Unref()
Definition: LuaRef.cpp:39