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?

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
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:

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

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