Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Sort Table By Property

I have not seen any documentation on sorting a table based on a property in the objects of the table, a real world example where I would want to use this is to control when to draw sprites based on the Z position.

Example:

pool[1].z = 500
pool[2].z = 200
-- sort table by Z property
print(pool[1].z) -- prints 200
print(pool[2].z) -- prints 500
like image 492
Cherry Avatar asked Sep 15 '25 00:09

Cherry


1 Answers

You need to use table.sort with a custom function for sorting where you compare the fields you need:

table.sort(pool, function(a, b) return a.z < b.z end)
like image 100
Paul Kulchenko Avatar answered Sep 17 '25 01:09

Paul Kulchenko