Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Picking a player with the biggest value?

Hello ScriptingHelpers,

I'm making a game where every round a random player is being picked. I don't use math.random() because it has limits and downsides (it's repetitive and I couldn't make something like 2x chance gamepass). I've managed to come up with this but I can't figure out how to sort table by table's table[1]s instead of comparing the whole tables which would make an error. Basically I need to get player that has the biggest chance and the chance value itself.

chances = {}
for _, a in pairs(game.ServerStorage.Players:GetChildren())do -- I'm storing folders named as player names and I have a number value (Chance of being picked) there
	table.insert(chances, {a.Chance.Value, a.Name})
end
table.sort(chances)
print(chances[#chances][1] .. " " .. chances[#chances][2])

Thank you for your time.

2 comments

0

Just add more of the same user in the table!

0

But I need them seperated

1 answer

You need to use the table.sort's 2nd argument, like this:

table.sort(chances, function(a, b) return a[1] < b[1] end)

I'm not sure if you already have this figured out, but it sounds like you would benefit from weighted randoms to give some options more weight than others (ie make them more likely to be selected); if you want more information, see my answer to this question: https://scriptinghelpers.org/questions/48345/how-to-deal-with-probabilities-such-as-loot-spawning-system

hiimgoodpack's idea would also work -- for every "chance" you wish to give someone, simply add their player to a table and use math.random on that:

function GetChances(player)
	return 1 -- todo: change this to fit your situation
end
function GetRandomPlayer()
	local p = game.Players:GetPlayers()
	local ps = {} -- player selection table
	for i = 1, #p do
		for j = 1, GetChances(p[i]) do
			table.insert(ps, p[i])
		end
	end
	return ps[math.random(1, #ps)]
end

This discussion is preserved as it was. New answers, comments, and votes are closed.