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

How do i make a math.random() go through a table until it finds an option that isn't taken?

Asked by
SkiH1gh 14
3 years ago

So for my game kind of like lt2, i need to cycle through a table of tree models. inside those models i have a bool value set to false by default. I got the table by doing game.ReplicatedStorage.OakTrees:GetChildren() and I want to do a math.random() to go through it but if i check if the value is false, how do i make it do math.random again? because if it does that and its still false, it could keep the process going and i dont want to have like 1 million else statements. Thanks for the help!

0
Also, you cant do a while true do local random = math.random(1,#game.ReplicatedStorage.OakTrees:GetChildren()) if random.Taken.Value == false then --code end end SkiH1gh 14 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

Sounds like you need to use a repeat ... until loop. Which would fit into your case like this:

local trees = workspace.Trees:GetChildren()
local option

repeat
    option = trees[math.random(1, #trees)]
until
    option.BoolValue.Value == true  

If I were you, I'd use a for i,v in pairs loop instead:

function getFirstTree()
    for index, value in pairs(trees:GetChildren()) do
        if value.BoolValue.Value == true then
            return value
        end
    end
end

local option = getFirstTree()
0
Ad

Answer this question