I'm trying to have the game select two children from a model. I want it to select one, then select a different one (such as two flavors of tea). The script for choosing the first works perfectly, but then I have it chose a second item using a Repeat (in case it chooses the first object again, as I want two unique choices). However, the chosen2 variable is 'nil' when I ask it to print after 'until.' I feel like I may be missing something obvious here but I'm not sure. Any explanation for this?
01 | function Choose 2 (Chosen 1 ) |
02 | print (Chosen 1 ) --prints the name of the first chosen object fine, such as "Peppermint" |
03 | repeat |
04 |
05 | local Chosen 2 = (Items [ math.random( 1 ,#Items) ] ) |
06 | print (Chosen 2 ) -- prints the name of the second chosen object fine, such as "Earl Grey" |
07 | until Chosen 2 ~ = Chosen 1 |
08 | print (Chosen 2 ) -- prints nil |
09 |
10 |
11 |
12 | end |
Like Painter said it's much better removing the values from your table and getting a random value out of that, however you should never edit the original table otherwise you'll lose your values forever. Instead I recommend making something called a "shallow copy".
It's basically a clone of your original table key and value pairs, only thing we need to do is make sure that Chosen1 is not within this clone which is easy:
01 | local teas = { "Mint" , "Grey" , "Strawberry" , "God knows what" } |
02 |
03 | local first = teas [ 1 ] -- This would be the Chosen1 value |
04 |
05 | function Choose 2 (Chosen 1 ) |
06 | local otherTeas = GetTableWithout(teas, Chosen 1 ) |
07 | print ( unpack (otherTeas)) |
08 |
09 | local Chosen 2 = otherTeas [ math.random( 1 , #otherTeas) ] |
10 | print (Chosen 1 ) |
11 | print (Chosen 2 ) |
12 | end |
13 |
14 | function GetTableWithout(t, value) |
15 | local t 2 = { } |
This is the basic idea behind it