Test object identity with shared_ptr_converter.
[luabind.git] / luabind / detail / ref.hpp
blob3edbfebfb25cce6aeaac835e69b4e466a56d5663
1 // Copyright (c) 2003 Daniel Wallin and Arvid Norberg
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:
10 // The above copyright notice and this permission notice shall be included
11 // in all copies or substantial portions of the Software.
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.
24 #ifndef LUABIND_REF_HPP_INCLUDED
25 #define LUABIND_REF_HPP_INCLUDED
27 #include <cassert>
28 #include <algorithm>
30 #include <luabind/config.hpp>
31 #include <luabind/lua_include.hpp>
33 namespace luabind
36 namespace detail
39 struct lua_reference
41 lua_reference(lua_State* L_ = 0)
42 : L(L_)
43 , m_ref(LUA_NOREF)
45 lua_reference(lua_reference const& r)
46 : L(r.L)
47 , m_ref(LUA_NOREF)
49 if (!r.is_valid()) return;
50 r.get(L);
51 set(L);
53 ~lua_reference() { reset(); }
55 lua_State* state() const { return L; }
57 void operator=(lua_reference const& r)
59 // TODO: self assignment problems
60 reset();
61 if (!r.is_valid()) return;
62 r.get(r.state());
63 set(r.state());
66 bool is_valid() const
67 { return m_ref != LUA_NOREF; }
69 void set(lua_State* L_)
71 reset();
72 L = L_;
73 m_ref = luaL_ref(L, LUA_REGISTRYINDEX);
76 void replace(lua_State* L_)
78 lua_rawseti(L_, LUA_REGISTRYINDEX, m_ref);
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
87 assert(m_ref != LUA_NOREF);
88 assert(L_);
89 lua_rawgeti(L_, LUA_REGISTRYINDEX, m_ref);
92 void reset()
94 if (L && m_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, m_ref);
95 m_ref = LUA_NOREF;
98 void swap(lua_reference& r)
100 assert(r.L == L);
101 std::swap(r.m_ref, m_ref);
104 private:
105 lua_State* L;
106 int m_ref;
111 #endif // LUABIND_REF_HPP_INCLUDED