I need help with id generator

Hello! I am making a game where a random id has to be generated, and all id’s have to be unique. I have tried multiple ways to check if the id already exists, but it errored or didn’t work.

What is the best method for this?

What kind of id? can it have numbers and characters, or just numbers, etc?

function pseudoRandomID (lastNumber)
  return lastNumber+1
end

Why do you need those really random ids anyways?
Just give them in a sequence.

It’s just numbers

30CharCapRoblox:(

I don’t know. The problem i have is that i don’t know how to check if an id already exists

local dataStore = dataStoreStuff

local lastId = dataStore:GetAsync("lastId")

function getnewId()
    local newId = lastId + 1
    lastId = newId
    return newId
end
---player's ain't gonna realize that it isn't random anyways

I haven’t tested this and typed it in here so there could be a syntax error, but here’s a simplified way to do this.

local ids = {} -- or a data store with all of the ids already made

function generateCode()
	local code = math.random(1,1000000000) -- for testing, there are better ways
	-- now we check if it exists
	if table.find(ids, code) then
        task.wait()
		generateCode() -- call the function again
	else
        table.insert(ids, code)
		return code
	end
end

local newCode = generateCode()
4 Likes

Thank you, this will work. I did not know about table.find()

2 Likes

You could use HttpService:GenerateGUID.

I’d be inclined to agree, you may as well use built-ins if they already exist (no need to reinvent the wheel).
https://developer.roblox.com/en-us/api-reference/function/HttpService/GenerateGUID

1 Like

Is the GUID always unique?

Need30chars

2 Likes
1 Like

It says there that storing the GUID’s are necessary, but I won’t get it to work

1 Like

Rather than creating an entire function, you should just use GenerateGUID, as this is its intended purpose. Also, the chances of two GUIDs being the same are 1 in 2 to the power of 128, basically impossible odds.

1 Like

No, however the chance of a collision is extremely low as I have been told. The best way to use the UUID system is to generate an ID and see if it’s already in use. If it’s not, then go ahead and use it.

1 Like