Change Key in Table

Heya! I’m currently working on a voting system, and I’m trying to set the key to the player object, and the value to the amount of votes they have. Is there anyway I can do this? I’ve tried

VoteTable[i] = v

but it seemed to changed the value and not the actual key.

function GameFunction.CalculateVotes(Table)
	local VoteTable = {}
	local Highest = 0;
	local Winner = nil;
	
	for i, v in pairs(Table) do
		table.insert(VoteTable, v.PlayerInfo.Votes.Value)
		VoteTable[i] = v
	end
	task.wait()
	for i, v in pairs(VoteTable) do
		if i > Highest then
			Highest = i
			Winner = v
		end	
	end
	print(VoteTable)
	print(Winner)
	return Winner
end

Two ways:

  1. Call a locksmith
  2. Delete the old key value pair and replace it with a new one, like:
tbl.NewKey = tbl.OldKey
tbl.OldKey = nil

So it’d be like this?

	for i, v in pairs(Table) do
		table.insert(VoteTable, v.PlayerInfo.Votes.Value)
	
		VoteTable[v] = VoteTable[i]
		VoteTable[i] = nil
	end
1 Like