lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Jan 7, 2011, at 8:49 PM, GrayFace wrote:

> On 07.01.2011 21:36, Mark Hamburg wrote:
>> If your C code needs to reference a Lua value, I tend to recommend using light userdata keys in the registry bearing in mind that this creates anchors for the GC.
> Where can I read more about these GC anchors?

Better choice of verbiage "roots". I blanked on that when I wrote my message yesterday.

On the broader point of issues with refs is that they are horrendously unsafe if you work with multiple universes since the id spaces are overlapping. If you have a thread-safe atomic counter, you could build a ref system equivalent that wouldn't have this problem as follows:

	int makeRef( lua_State* L, int stackIndex ) {
		int id = atomic_increment( &gIDCounter );
		lua_pushvalue( L, stackIndex );
		lua_rawseti( L, LUA_REGISTRYINDEX, id );
		return id;

	void destroyRef( lua_State* L, int id ) {
		lua_rawgeti( L, LUA_REGISTRYINDEX, id );
		assert( !lua_isnil( L, -1 ), "Mismatched Lua state and id passed to destroyRef" );
		lua_pop( L, 1 );
		lua_pushnil( L );
		lua_rawseti( L, LUA_REGISTRYINDEX, i );

If int's aren't big enough, then use a 64-bit atomic counter and fit it into the 53-bit integer support within a double.

But most of the time there is some value you can use as a light userdata key and avoid the whole issue.