My Project
ref.hpp
1 // Copyright (c) 2003 Daniel Wallin and Arvid Norberg
2 
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the "Software"),
5 // to deal in the Software without restriction, including without limitation
6 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 // and/or sell copies of the Software, and to permit persons to whom the
8 // Software is furnished to do so, subject to the following conditions:
9 
10 // The above copyright notice and this permission notice shall be included
11 // in all copies or substantial portions of the Software.
12 
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
14 // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
15 // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
16 // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17 // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
18 // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
21 // OR OTHER DEALINGS IN THE SOFTWARE.
22 
23 
24 #ifndef LUABIND_REF_HPP_INCLUDED
25 #define LUABIND_REF_HPP_INCLUDED
26 
27 #include <cassert>
28 #include <algorithm>
29 
30 #include <luabind/config.hpp>
31 #include <luabind/lua_include.hpp>
32 
33 namespace luabind
34 {
35 
36 namespace detail
37 {
38 
40  {
41  lua_reference(lua_State* L_ = 0)
42  : L(L_)
43  , m_ref(LUA_NOREF)
44  {}
46  : L(r.L)
47  , m_ref(LUA_NOREF)
48  {
49  if (!r.is_valid()) return;
50  r.get(L);
51  set(L);
52  }
53  ~lua_reference() { reset(); }
54 
55  lua_State* state() const { return L; }
56 
57  void operator=(lua_reference const& r)
58  {
59  // TODO: self assignment problems
60  reset();
61  if (!r.is_valid()) return;
62  r.get(r.state());
63  set(r.state());
64  }
65 
66  bool is_valid() const
67  { return m_ref != LUA_NOREF; }
68 
69  void set(lua_State* L_)
70  {
71  reset();
72  L = L_;
73  m_ref = luaL_ref(L, LUA_REGISTRYINDEX);
74  }
75 
76  void replace(lua_State* L_)
77  {
78  lua_rawseti(L_, LUA_REGISTRYINDEX, m_ref);
79  }
80 
81  // L may not be the same pointer as
82  // was used when creating this reference
83  // since it may be a thread that shares
84  // the same globals table.
85  void get(lua_State* L_) const
86  {
87  assert(m_ref != LUA_NOREF);
88  assert(L_);
89  lua_rawgeti(L_, LUA_REGISTRYINDEX, m_ref);
90  }
91 
92  void reset()
93  {
94  if (L && m_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, m_ref);
95  m_ref = LUA_NOREF;
96  }
97 
98  void swap(lua_reference& r)
99  {
100  assert(r.L == L);
101  std::swap(r.m_ref, m_ref);
102  }
103 
104  private:
105  lua_State* L;
106  int m_ref;
107  };
108 
109 }}
110 
111 #endif // LUABIND_REF_HPP_INCLUDED
112 
Definition: ref.hpp:39
Definition: minilua.c:461
Definition: PEtypes.h:507