How would you go about doing this in lua? To make it simple, this is an example of a random player selection.
local p = game.Players:GetPlayers() local rnd = math.random(1,#p) print (p[rnd].Name)
How can I make a percentage based for each player but as an array? For example, Dave has 15% chance of being selected, Steve has 65% chance of being selected, Bert has 20% chance of being selected.
My run at it:
local percent = {0.15, 0.65,0.2} local player = {"Dave", "Steve", "Bert"} local select local total = 0 for i = 1, #percent do total = total + percent[i] end local rnd = math.random(1,100)/100 print(rnd) for j = 1, #percent do local prev = percent[j-1] or 0 print(prev) if prev >= rnd and rnd <= percent[j] then select = player[j] break; end end print(select)
EDIT: Modified code above, doesn't work accordingly :P
math.random()
(with no parameters) generates any number in the range [0,1).
To select among weighted events, you compute a random value from 0 to the sum of the weights:
local totalweight = 0; for _, v in ipairs(percent) do totalweight = totalweight + v; end local at = math.random() * totalweight;
(Depending on how you generate your percent
you could possibly skip this calculation step, if, for instance, you know it will always add up to one)
We then look at our list and can think of it as a numberline. Each item 'owns' a portion of the line from 0 to totalweight
, and at
is some random place in between. To find which place, we can do something like this:
local where = 0; for i, v in ipairs(percent) do if at < v then where = i; break; end at = at - v; end
Then, where
is the corresponding chosen index from percent
.