Cherry
Cherry

Reputation: 43

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

Upvotes: 4

Views: 1000

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

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)

Upvotes: 6

Related Questions