Why is my table sorting showing up as nil?

local Players = {
		{Kills = 2, Player = "DevFoll"},
		{Kills = 2, Player = "Cap"},
		{Kills = 3, Player = "John"},
		{Kills = 1, Player = "Jacob"},
	}
	print(Players)
	table.sort(Players, function(a,b)
		return a[1] > b[1]
	end)


	for i,v in pairs(Players) do
		print(v[1], v[2])
	end

First it prints the table correctly
then at the last code it prints nil nil

Hello, you’re attempting to reference a dictionary of elements by numbers, which is unfortunately not how it works. Each table has its own Kills and Player index, which are not ordered by numbers. To reference an element, you can do either v.Kills or v["Kills"] etc.

Here would be a revised version of your sorting/printing code:

table.sort(Players, function(a,b)
	return a.Kills > b.Kills
end)

for i,v in pairs(Players) do
	print(v.Kills, v.Player)
end

Hope this helps!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.