LuaObject LuaGlobalSelector::toLuaObject( void ) const
{
	magicalAssert( !_key.empty(), "key should not be empty!" );
	lua_State* L = _L->cPtr();
	LuaObject lobj;
	lua_getglobal( L, _key.c_str() );

	switch( lua_type( L, -1 ) )
	{
	case LUA_TNIL:
		lobj = nullptr;
		break;
	case LUA_TBOOLEAN:
		lobj = (bool) lua_toboolean( L, -1 );
		break;
	case LUA_TNUMBER:
		lobj = (double) lua_tonumber( L, -1 );
		break;
	case LUA_TSTRING:
		lobj = lua_tostring( L, -1 );
		break;
	case LUA_TUSERDATA:
		{
			int top = lua_gettop( L );
			std::string type = tolua_typename( L, top );
			lua_pop( L, 1 );
			void* userdata = tolua_tousertype( L, top, 0 );
			lobj.set( userdata, type.c_str() );
		}
		break;
	case LUA_TFUNCTION:
		{
			LuaFunction lf;
			int handler = tolua_ext_tofunction( L, lua_gettop( L ), 0 );
			if( handler != 0 )
			{
				lf.bind( _L, handler );
			}
			lobj = lf;
		}
		break;
	case LUA_TTABLE:
		{
			LuaTable lt;
			int handler = tolua_ext_totable( L, lua_gettop( L ), 0 );
			if( handler != 0 )
			{
				lt.bind( _L, handler );
			}
			lobj = lt;
		}
		break;
	default:
		lobj = nullptr;
		break;
	}
	lua_pop( L, 1 );
	return lobj;
}
LuaTable LuaGlobalSelector::toLuaTable( void ) const
{
	magicalAssert( !_key.empty(), "key should not be empty!" );
	lua_State* L = _L->cPtr();
	LuaTable lt;
	lua_getglobal( L, _key.c_str() );

	int handler = tolua_ext_totable( L, lua_gettop( L ), 0 );
	if( handler != 0 )
	{
		lt.bind( _L, handler );
	}
	lua_pop( L, 1 );
	return lt;
}
LuaTable LuaTableSelector::toLuaTable( void ) const
{
	magicalAssert( !_key.empty(), "key should not be empty!" );
	if( !_L || !_handler ) 
		return nullptr;

	LuaTable lt;
	lua_State* L = _L->cPtr();
	tolua_ext_get_table_by_handler( L, _handler );

	lua_getfield( L, -1, _key.c_str() );
	int handler = tolua_ext_totable( L, lua_gettop( L ), 0 );
	if( handler != 0 )
	{
		lt.bind( _L, handler );
	}
	lua_pop( L, 2 );
	return lt;
}