Search code examples
luatabletop-simulator

How to order a Table to tables based on 1 single data part of it?


I am a hobbyest making mods in TableTop Simulator using LUA and have a question that I can not seam to work out.

I have a number of "objects" which is a table in TTS that contains various data for those objects. For example.. obj.position = {x,y,z}... and can be accessed at the axis level as well.

obj.position = {5,10,15} -- x,y,z
obj.position.x == 5

This is an example. The makers of TTS have made it so you can access all the parts like that. So I can acess the object.. and then its various parts. There is a heap, like name, mesh, difuse and a ton more. roations{x,y,z} etc etc

Anyway. I have a table of objects... and would like to order those objects based on the positional data of the x axis.. so highest to lowest. So if I have a table and obj1 in that table is x=3 and obj2 is x=1 and obj3 = x=2 it would be sorted as obj2,obj3,obj1

Pseudo code:

tableOfObjects = {obj1,obj2,obj3}
--[[
tableOfObjectsp[1] == obj1
tableOfObjectsp[2] == obj2
tableOfObjectsp[3] == obj3

tableOfObjectsp[1].position.x == 3
tableOfObjectsp[2].position.x == 1
tableOfObjectsp[4].position.x == 2
--]]
---After Sort it would look this list
tableOfObjects = {obj1,obj3,obj2}
    --[[
tableOfObjectsp[1] == obj1
tableOfObjectsp[2] == obj3
tableOfObjectsp[3] == obj2

tableOfObjectsp[1].position.x == 3
tableOfObjectsp[2].position.x == 2
tableOfObjectsp[3].position.x == 1
--]]

I hope I am making sense. I am self taught in the last few months!

So basically I have a table of objects and want to sort the objects in that table based on a single value attached to each individual object in the table. In this case the obj.position.x

Thanks!


Solution

  • You need table.sort. The first argument is the table to sort, the second is a function to compare items.

    Example:

    t = {
        {str = 42, dex = 10, wis = 100},
        {str = 18, dex = 30, wis = 5}
    }
    
    table.sort(t, function (k1, k2)
        return k1.str < k2.str
    end)
    

    This article has more information