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?
01 | Values = { "Hi1" , "Hi2" , "Hi3" , "Hi4" , "Hi5" , "Hi6" } |
02 | print (#Values) -- Returns 6 values |
03 |
04 | --Repeat x3 with different variable names |
05 | ChosenValue 1 = Values [ math.random( 1 , #Values) ] |
06 | removethis 1 = Values [ ChosenValue 1 ] |
07 | table.remove(Values, removethis 1 ) |
08 | print (ChosenValue 1 , "Value1" ) |
09 | -- |
10 |
11 | --At the end I check in table how many are left |
12 | 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?
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.
01 | Values = { "Hi1" , "Hi2" , "Hi3" , "Hi4" , "Hi5" , "Hi6" } |
02 | print (#Values) -- Returns 6 values |
03 |
04 | --Repeat x3 with different variable names |
05 | local i = math.random( 1 , #Values); -- Chosen index |
06 | ChosenValue 1 = table.remove(Values, i) -- table.remove actually returns the value it removed. |
07 | print (ChosenValue 1 , "Value1" ) |
08 | -- |
09 |
10 | --At the end I check in table how many are left |
11 | print (#Values) --Returns 2, it is less, but it still picks ones that are already removed, how can I prevent this? |