why does this function not get weights which are 0.4 for example
local function RandomFromWeightedTable(OrderedTable)
local TotalWeight = 0
for Piece, Weight in pairs(OrderedTable) do
TotalWeight = TotalWeight + Weight
end
local Chance = math.random(0, TotalWeight)
local Counter = 0
for Piece, Weight in pairs(OrderedTable) do
Counter = Counter + Weight
if Chance <= Counter then
return Piece
end
end
end
local function RandomFromWeightedTable(OrderedTable)
local TotalWeight = 0
for Piece, Weight in pairs(OrderedTable) do
TotalWeight = TotalWeight + Weight
end
local RandomFloat = math.random()
local Chance = RandomFloat * TotalWeight
local Counter = 0
for Piece, Weight in pairs(OrderedTable) do
Counter = Counter + Weight
if Chance <= Counter then
return Piece
end
end
end
i’ve fixed it, just generated a random float, and multiplied by total weight