2016-05-18 56 views
0

好吧,所以即時通訊製作一個關注的朋友GUI的東西,即時通訊嘗試從名稱中使用GetUserIdFromNameAsync的字符串。即時嘗試電腦,所以我沒有得到錯誤,但它返回零,即使它的名字,我知道的作品,因爲我經常在上面打電話。並且它返回打印中的id,但是當我嘗試pcall時,然後使用它,如果它每次返回nil並轉到我的else語句。pcall a GetUserIdFromNameAsync()

local TeleportService = game:GetService("TeleportService") 

script.Parent.OnServerEvent:connect(function(player, id) 
    place = player.GuiFolder 
    print(game.Players:GetUserIdFromNameAsync(id)) 
    --ISSUE IN LINE BELOW-- ISSUE IS IN THE LINE BELOW 
    friend, msg = pcall(game.Players:GetUserIdFromNameAsync(id)) 
    if friend then 
    print(player.Name, player, player.PlayerGui.MainMenu.Name) 
    if player:IsFriendsWith(friend) then 
     place.IsFriend.Value = true 
     local success, errorMsg, placeId, instanceId = TeleportService:GetPlayerPlaceInstanceAsync(friend) 
      if success then 
       place.foundplayerbar.Value = "Found player. Would you like to join?" 
       place.Activated.Value = true 
      else enter code here 
       place.errorbar.Value = "ERROR: Player not online!" 
      end 
     else place.errorbar.Value = "ERROR: Not Friends with person!" 
    end 
    else place.errorbar.Value = "ERROR: Player doesn't exist!" 
    end 
end) 

回答

1

根據「規劃在Lua」電子書:「假設你想運行一段Lua代碼和捕捉任何錯誤引發,同時運行這些代碼的第一步是封裝了一段代碼英寸一個函數... pcall函數在保護模式下調用它的第一個參數,以便在函數運行時捕獲任何錯誤如果沒有錯誤,pcall返回true,加上任何由調用返回的值,否則返回錯誤,加上錯誤信息。「

而是直接在函數調用PCALL的,在功能的第一封裝的一切:

function func() 
    friend, msg = game.Players:GetUserIdFromNameAsync(id) 
    if friend then 
     ... 
    else 
     ... 
    end 
end 

然後就可以調用與PCALL功能和捕捉任何錯誤:

local status, err = pcall(func) 
if not status then print(err) end 
0

從Lua中文檔:

假設您想運行一段Lua代碼並捕獲任何錯誤運行該代碼時引發的。你的第一步是將這段代碼封裝在一個函數中;讓我們把它叫做foo ...那麼,與您通話PCALL富...

代碼使用PCALL具有的功能,但它調用的函數,而不是使用它作爲一個參數。

爲了解決這個問題,你可以把game.Players:GetUserIdFromNameAsync(id)在功能和使用它作爲參數,而是一個更簡單的方法是使用匿名函數,像

friend, msg = pcall(function() 
    game.Players:GetUserIdFromNameAsync(id) 
end) 

它會給你正確的值。

相關問題