1 #ifndef _library__lua_pin__hpp__included__
2 #define _library__lua_pin__hpp__included__
4 #include "lua-base.hpp"
9 * Pin of an object against Lua GC.
11 template<typename T
> struct objpin
24 * Parameter _state: The state to pin the object in.
25 * Parameter _object: The object to pin.
27 objpin(state
& lstate
, T
* _object
)
28 : _state(&lstate
.get_master())
30 _state
->pushlightuserdata(this);
31 _state
->pushvalue(-2);
32 _state
->rawset(LUA_REGISTRYINDEX
);
41 _state
->pushlightuserdata(this);
43 _state
->rawset(LUA_REGISTRYINDEX
);
49 objpin(const objpin
& p
)
54 _state
->pushlightuserdata(this);
55 _state
->pushlightuserdata(const_cast<objpin
*>(&p
));
56 _state
->rawget(LUA_REGISTRYINDEX
);
57 _state
->rawset(LUA_REGISTRYINDEX
);
61 * Assignment operator.
63 objpin
& operator=(const objpin
& p
)
65 if(_state
== p
._state
&& obj
== p
.obj
)
68 throw std::logic_error("A Lua object can't be in two lua states at once");
70 _state
->pushlightuserdata(this);
72 _state
->rawset(LUA_REGISTRYINDEX
);
76 _state
->pushlightuserdata(this);
77 _state
->pushlightuserdata(const_cast<objpin
*>(&p
));
78 _state
->rawget(LUA_REGISTRYINDEX
);
79 _state
->rawset(LUA_REGISTRYINDEX
);
85 * Clear a pinned object.
90 _state
->pushlightuserdata(this);
92 _state
->rawset(LUA_REGISTRYINDEX
);
98 * Get pointer to pinned object.
100 * Returns: The pinned object.
102 T
* object() { return obj
; }
106 operator bool() { return obj
!= NULL
; }
110 T
& operator*() { if(obj
) return *obj
; throw std::runtime_error("Attempted to reference NULL Lua pin"); }
111 T
* operator->() { if(obj
) return obj
; throw std::runtime_error("Attempted to reference NULL Lua pin"); }
115 void luapush(state
& lstate
)
117 lstate
.pushlightuserdata(this);
118 lstate
.rawget(LUA_REGISTRYINDEX
);
125 template<typename T
> void* unbox_any_pin(struct objpin
<T
>* pin
)
127 return pin
? pin
->object() : NULL
;