How to sort a table of a lua object according to if a property exists

I’m trying to sort out a table called “members” in a descending order according to if they have a “vip” property or not, so I tried to do the following:

table.sort(members, function(a, b)
	return a.vip ~= nil
end)

which returns true if a has vip, and false if not(so move the member up if they have vip, else push them down).

However, trying the above I’m getting treated with the “invalid order function for sorting” error. So my question is clear, how can I order tables(in this case members) according to if a property within them exists or not?

You can’t sort a dictionary, you can only sort arrays/lists. The documentation says so.

No, a and b are dictionaries, members is an array that contains them. And when dictionaries are within an array they can be sorted when comparing properties, like in this scenario:

table.sort(members, function(a, b)
	return a.coins > b.coins 
end)

but I can’t figure out how to make it work for the use case mentioned above.

For some reason, I’m not getting the same error as you when I’m sorting the table, could you show what your members table is structured like?

Edit: I needed to put more objects in my array to get the error, I’ll keep testing until I can find a solution.

1 Like

Found a solution:

table.sort(members, function(a, b)
	return a.vip and not b.vip
end)

It had problems when comparing two tables that both had their VIP values, so you need to add an extra statement that checks if b.vip doesn’t exist too.

Returning true = shift value up, false = shift value down.

1 Like

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