PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

GetUserIdFromNameAsync

GetUserIdFromNameAsync will send a query to the Roblox website asking what the user ID is of the account with the given name. This function does not cache; it always sends a web request even if a username was already queried or if the player is already connected to the server (and thus has their Player/UserId exposed).

This method errors if no account exists with the given username. If you aren’t certain such an account exists, it’s recommended to wrap calls to this function with pcall. In addition, you can manually cache results to make future calls with the same username fast. See the code samples to learn how to do this.

Parameters

Name Type Default Description

The username of the player being specified.

Returns

Return Type Summary

The userId of a user whose name is specified.


Code Samples


User ID Lookup

This code sample demonstrates memoization (not memorization!) of the GetUserIdFromNameAsync method. It uses a table to cache the results of the function. It also uses pcall in case the username doesn’t exist.

local Players = game:GetService("Players")

-- Memoization: since these results are rarely (if ever) going to change
-- all we have to do is check a cache table for the name.
-- If we find the name, then we have no work to do! Just return the user id (fast).
-- If we don't find the name (cache miss), go look it up (takes time).
local cache = {}
function getUserIdFromUsername(name)
	-- First, check if the cache contains the name
	if cache[name] then return cache[name] end
	-- Second, check if the user is already connected to the server
	local player = Players:FindFirstChild(name)
	if player then
		cache[name] = player.UserId
		return player.UserId
	end 
	-- If all else fails, send a request
	local id
	pcall(function ()
		id = Players:GetUserIdFromNameAsync(name)
	end)
	cache[name] = id
	return id
end

print(getUserIdFromUsername("Ozzypig")) --> 269323
print(getUserIdFromUsername("Ozzypig")) --> 269323, but this one returns much quicker
print(getUserIdFromUsername("Shedletsky")) --> 261