#string value error idk why
1 messages · Page 1 of 1 (latest)
type Choice = {item: string, weight: number}
local WeightedSystem = {}
WeightedSystem.__index = WeightedSystem
function WeightedSystem.__call(_: any, list: {Choice})
return setmetatable({list = list}, WeightedSystem)
end
function WeightedSystem:totalWeight(): number
local t = 0
for _, v in ipairs(self.list) do
t += math.max(0, v.weight)
end
return t
end
function WeightedSystem:pick(): string
local total = self:totalWeight()
local roll = math.random() * total
local acc = 0
for _, v in ipairs(self.list) do
acc += v.weight
if roll <= acc then
return v.item
end
end
return self.list[1].item
end
setmetatable(WeightedSystem, WeightedSystem)
math.randomseed(os.clock() * 1e6)
local selections: {Choice} = {
{item = "Wood", weight = 0},
{item = "Stone", weight = -1},
{item = "Metal", weight = 0},
}
local picker = WeightedSystem(selections)
local chosen = picker:pick()
chosen():upper()```