Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

table.remove and math.random error?

Asked by 8 years ago

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 answer

Log in to vote
1
Answered by 8 years ago

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?
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. Evadable 65 — 8y
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. User#6546 35 — 8y
0
Ohhhh, makes so much more sense, at first I thought you were contradicting yourself, thanks for the help. Evadable 65 — 8y
Ad

Answer this question