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

How do I carry a variable past 'Until'?

Asked by 5 years ago

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?

01function Choose2 (Chosen1)
02    print (Chosen1) --prints the name of the first chosen object fine, such as "Peppermint"
03repeat
04 
05local Chosen2 = (Items[math.random(1,#Items)])
06print(Chosen2) -- prints the name of the second chosen object fine, such as "Earl Grey"
07until Chosen2 ~= Chosen1
08    print (Chosen2) -- prints nil
09 
10 
11 
12end
1
Why make it so complicated? I see what you're trying to do. You dont want them to be equal but why dont you remove the chosen1 out of the table then? This way it would remove 1 item from the table ( chosen1 ) and chosen2 could never take the same as chosen1 because it is not in the table anymore. Paintertable 171 — 5y

1 answer

Log in to vote
2
Answered by 5 years ago
Edited 5 years ago

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:

01local teas = {"Mint", "Grey", "Strawberry", "God knows what"}
02 
03local first = teas[1] -- This would be the Chosen1 value
04 
05function Choose2(Chosen1)
06    local otherTeas = GetTableWithout(teas, Chosen1)
07    print(unpack(otherTeas))
08 
09    local Chosen2 = otherTeas[math.random(1, #otherTeas)]
10    print(Chosen1)
11    print(Chosen2)
12end
13 
14function GetTableWithout(t, value)
15    local t2 = {}
View all 24 lines...

This is the basic idea behind it

0
Thank you! This method looks a lot more efficient than the way I was trying to handle it, and I'll definitely try going this route instead. Just for the sake of getting better at LUA though, I'm still wondering why my repeat loop couldn't carry out a variable. OswinFalls 69 — 5y
Ad

Answer this question