How to get a random string from a list that isn't currently being used?

Hey,

My game requires server/colony names, and the names need to be randomly picked from a list. However, I don’t want duplicate names. How can I automatically reroll the names until it’s not a duplicate?

If with “duplicate names” you mean you don’t want the same name multiple times, then you can do something like this:

index = math.random(1,#table)
item = table[index]
table.remove(table, item) -- prevents returning identical "item"
return item

You can also make a copy of the table and do such to prevent permanently erasing items from the table.

Let me know if this solved your question!

1 Like

Well, I mean sorta.

I want to just set a name as “Occupied” once it’s been used in a savefile.

Basically if you roll a random name, and it’s taken, it should reroll until it’s not.

Maybe this is a problem at the core of my game, since it relies on having a massive list of names which needs to be expanded on once I get more players. The problem is that my current Ui is already somewhat complex (3d hologram) and adding a naming textbox would involve adding another window to the 3 on a single panel.

Oh, I see! Then you might want to do something like this:

while true do
local index = math.random(1,#table)
local item = table[index]
if item ~= "Occupied" then
    return item -- breaks the loop and returns item
end
end

you can also use a “repeat until” loop. And yes, having so many variables isn’t necessary. It’s just better for customization.
Personally I wouldn’t recommend doing something like this, as you can hypothetically exhaust execution time and technically crash if there are little to no slots that aren’t “Occupied”.

Also, sorry, I didn’t really get what you mean with your edit. I can help you with it, if you want to explain it in more depth.

1 Like

Thanks for the help, I’m just decided to redesign my Ui and add a naming feature.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.