Initial revision
[luabind.git] / luabind / detail / ref.hpp
blob0d39df29a23eb294aedfa1d8e45608e58203f5d4
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 <luabind/config.hpp>
29 namespace luabind { namespace detail
32 // based on luaL_ref from lauxlib.c in lua distribution
33 inline int ref(lua_State *L)
35 int ref;
36 if (lua_isnil(L, -1))
38 lua_pop(L, 1); /* remove from stack */
39 return LUA_REFNIL; /* `nil' has a unique fixed reference */
42 lua_rawgeti(L, LUA_REGISTRYINDEX, 0); /* get first free element */
43 ref = (int)lua_tonumber(L, -1); /* ref = t[0] */
44 lua_pop(L, 1); /* remove it from stack */
45 if (ref != 0)
46 { /* any free element? */
47 lua_rawgeti(L, LUA_REGISTRYINDEX, ref); /* remove it from list */
48 lua_rawseti(L, LUA_REGISTRYINDEX, 0); /* (that is, t[0] = t[ref]) */
50 else
51 { /* no free elements */
52 lua_pushliteral(L, "n");
53 lua_pushvalue(L, -1);
54 lua_rawget(L, LUA_REGISTRYINDEX); /* get t.n */
55 ref = (int)lua_tonumber(L, -1) + 1; /* ref = t.n + 1 */
56 lua_pop(L, 1); /* pop t.n */
57 lua_pushnumber(L, ref);
58 lua_rawset(L, LUA_REGISTRYINDEX); /* t.n = t.n + 1 */
60 lua_rawseti(L, LUA_REGISTRYINDEX, ref);
61 return ref;
64 inline void unref(lua_State *L, int ref)
66 if (ref >= 0)
68 lua_rawgeti(L, LUA_REGISTRYINDEX, 0);
69 lua_rawseti(L, LUA_REGISTRYINDEX, ref); /* t[ref] = t[0] */
70 lua_pushnumber(L, ref);
71 lua_rawseti(L, LUA_REGISTRYINDEX, 0); /* t[0] = ref */
75 inline void getref(lua_State* L, int r)
77 lua_rawgeti(L, LUA_REGISTRYINDEX, r);
82 #endif // LUABIND_REF_HPP_INCLUDED