How would I go about making a weight based selection system in lua which accepts tables in this format and gives and output:
local input = {
{value = “option a”, weight = 10},
{value = “option b”, weight = 5},
{value = “option c”, weight = 20}
}
local output = someMagicalWeightBasedSelectionFunction(input)
print(output)
-- it’s gonna be probably “option c” with a chance of 20/35
There is absolutely nowhere on the internet where I can find an efficient weight based selection system in lua. It does not even have to be in the given format above, I can change it to my desire. Is there a weight based selection system in lua? If so, please let me know (linking to the source of the information would be recommended),
You can just make a weight based selection system easily like this, there is no built-in method for it!
function someMagicalWeightBasedSelectionFunction(input)
local chance = 0 -- first this will be the sum of all weights
for l,v in pairs(input) do
chance += v["weight"]
end
chance = math.random(chance) -- change 'chance' to pick random 0-chance
for l,v in pairs(input) do
chance -= v["weight"]
if chance <= 0 then -- check if it's less than or equal to 0, if so select this one
return(v["value"])
end
end
end
Luau now supports compound assignments ( += , -= , *= , /= , %= , ^= and ..= ). The assignments only work on single values ( a, b += 1 is invalid); the left hand side is only evaluated once. When modifying table keys, __index and __newindex will be called as necessary - no new metamethods are introduced.