Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

table.remove and math.random error?

Basically, I want to get a random value out of the table, but I don't want repeats, so I'm using table.remove(), is there a better way to do this or should I just continue with what I have and insert the values in later?

Values = {"Hi1", "Hi2", "Hi3", "Hi4", "Hi5", "Hi6"}
print(#Values) -- Returns 6 values

--Repeat x3 with different variable names
ChosenValue1 = Values[math.random(1, #Values)]
removethis1 = Values[ChosenValue1]
table.remove(Values, removethis1)
print(ChosenValue1, "Value1")
--

--At the end I check in table how many are left
print(#Values) --Returns 2, it is less, but it still picks ones that are already removed, how can I prevent this?

EDIT: Found out that removethis1 is nil, so therefore I guess, how do I get the location of ChosenValue1, or is there yet a better way to make sure there is no duplicates?

1 comment

1 answer

✓ Accepted answer

table.remove takes a number
It's not like Python, sadly.

The issue is that the argument you want to be supplying to table.remove is not removethis1 but instead the number used in Chosenvalue1, because it takes the index of the value it is supposed to remove instead of the value itself.

The reason for this is obvious: Keys are the only unique things in a table.


Values = {"Hi1", "Hi2", "Hi3", "Hi4", "Hi5", "Hi6"}
print(#Values) -- Returns 6 values

--Repeat x3 with different variable names
local i = math.random(1, #Values); -- Chosen index
ChosenValue1 = table.remove(Values, i) -- table.remove actually returns the value it removed.
print(ChosenValue1, "Value1")
--

--At the end I check in table how many are left
print(#Values) --Returns 2, it is less, but it still picks ones that are already removed, how can I prevent this?

3 comments

0

So is there a way to get the location of a random chosen variable from a table, or should I just accept duplicates, I'd prefer not to but it doesn't hurt me.

0

What I'd meant to write is that you want to use the number which Chosenvalue1 uses. I've updated my answer to show some example code.

0

Ohhhh, makes so much more sense, at first I thought you were contradicting yourself, thanks for the help.

This discussion is preserved as it was. New answers, comments, and votes are closed.