Weight based selection system in this format?

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! :slight_smile:

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
1 Like

I ate lunch and developed my own system, and even a way to prove that it is truley weight based (I didn’t see your response when I made it):

https://repl.it/talk/share/Weight-Based-Selection-System-Lua-inefficienct/82074

Since I am fimiliar with my own code, seems like I will be using mine, sorry about that kind responder.

Edit: I was looking at your post, it isn’t going to work. += isn’t in lua, so you can’t do that.

I’m pretty sure you’re using Luau in this context and not vanilla Lua.
Compound assignment works on Luau.
https://developer.roblox.com/en-us/resources/release-note/Release-Notes-for-435

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.

1 Like