In that case StingyDudeman’s explanation comes in handy.
local random = Random.new()
local wires = {
{color = "red"; wireType = nil};
{color = "blue"; wireType = nil};
{color = "green"; wireType = nil};
{color = "yellow"; wireType = nil};
}
local function GetRandomWireInfo()
return wires[random:NextInteger(1,#wires)]
end
local randomWireInfo = GetRandomWireInfo()
print(randomWireInfo.color)
Again, if you wanted to exclude certain numbers, let’s say red and green, it would be even easier then above, but again, it depends on your use case. Ask yourself, is it more valuable for you to have wires accessible by color name, e.g. wires.red
, or with numbers, which makes getting random number slightly easier, but wires are accessible by numeric indices, e.g. wires[1]
for red info, wires[1].wireType
etc.
local function GetRandomWireInfo(toExclude)
local randNum: number
repeat
randNum = random:NextInteger(1,4)
until not toExclude or not table.find(toExclude, randNum)
return wires[randNum]
end
local randomWireInfo = GetRandomWireInfo(table.pack(1,3,4)) -- always blue
Just to explain this repeat-loop condition:
until not toExclude or not table.find(toExclude, randNum)
When condition is true
, loop is going to finish. So if there is no toExlude
, then not nil
== true
. And if there is toExclude
, if table.find()
would return something, wouldn’t be nil
, so not something
== nothing
. If table.find()
doesn’t find the random integer in the table of integers to exclude, it will return nil
, and not nil
== something
, which means our loop can finish.
Happy ending