Players:GetUserIdFromNameAsync() is causing an error

Hello. I’m creating an admin script for my friend’s game and I’ve come across an error when trying to pcall (referenced here) a Players:GetUserIdFromNameAsync() function. However, when I print the pcall’s error message, it states attempt to call a number value. I’m confused by this because in the function I am putting a string which in this case is the Player’s name.

What I’m trying to achieve is pcall a function to ensure it does not error the script, and ban a player upon admin request. I’ve read all about pcall and Players:GetUserIdFromNameAsync() but I cannot seem to understand why this error is occurring.

v Snippet of my Code v

local success, errorStatement = pcall(game.Players:GetUserIdFromNameAsync(Player.Name))

print(success, errorStatement) -- returns **false attempt to call a number value**

if success == true then
	local UserId = game.Players:GetUserIdFromNameAsync(Player.Name.."~BanInfo")
	if Storage:GetAsync(UserId.."~BanInfo") == nil then
		Storage:SetAsync(UserId.."~BanInfo", {true, "You've been banned.", Player.UserId})
		Storage:SetAsync(UserId.."~BanInfo", {true, "You've been banned.", Player.UserId})

This is incorrect usage of pcall. You’re essentially running GetUserIdFromNameAsync from a normal script, and then running what is returned from that (in this case, a UserId) in a pcall. However, since a UserId is a number and not a function, it throws an error.

The correct way to do this would be local success, errorStatement = pcall(function() game.Players:GetUserIdFromNameAsync(Player.Name) end)


pcall() takes a function not an expression.


Since Players:GetUserIdFromNameAsync() returns a number and pcall expects to call a function, the error says attempt to call a number. To fix this use an anonymous function:

local success, returned = pcall(function()
    return game.Players:GetUserIdFromNameAsync(Player.Name)
-- Here returned will be the error if success == false and the UserId if success == true

Also, this line will error:

local UserId = game.Players:GetUserIdFromNameAsync(Player.Name.."~BanInfo")

since you concatenate "~BanInfo" for seemingly no reason, changing the provided name. To fix this, simply remove the concatenated string:

local UserId = game.Players:GetUserIdFromNameAsync(Player.Name)
1 Like

I see now. Thank you for the help!