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?
function Choose2 (Chosen1) print (Chosen1) --prints the name of the first chosen object fine, such as "Peppermint" repeat local Chosen2 = (Items[math.random(1,#Items)]) print(Chosen2) -- prints the name of the second chosen object fine, such as "Earl Grey" until Chosen2 ~= Chosen1 print (Chosen2) -- prints nil 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:
local teas = {"Mint", "Grey", "Strawberry", "God knows what"} local first = teas[1] -- This would be the Chosen1 value function Choose2(Chosen1) local otherTeas = GetTableWithout(teas, Chosen1) print(unpack(otherTeas)) local Chosen2 = otherTeas[math.random(1, #otherTeas)] print(Chosen1) print(Chosen2) end function GetTableWithout(t, value) local t2 = {} for k,v in pairs(t) do if v ~= value then table.insert(t2, v) end end return t2 end Choose2(first)
This is the basic idea behind it