How to detect lower element from a table?

Hello guys

I ve a problem. I ve a table like this

local Table = {} Table[1] = { x=200 } Table[2] = { x=259 } Table[3] = { x=-50} Table[4] = { x=150 } Table[5] = { x=-200 } Table[6] = { 170} Table[7] = { x=50} Table[8] = { x= -150 }

My task is to create a function that detect which is the element with the lower “x”.
 How can I do this?

You could either sort the table in order of x:

[lua]

local function sortTable(t)

    function compare(a, b)

        return a.x < b.x

    end

    table.sort(t, compare)

end

sortTable(myTable)

[/lua]

 

Or just loop through all the elements and compare the X values:

 

[lua]

 

local function findLowest (t)

      local lowestX = 9999

      local lowestElement

      for i = 1, #t, 1 do

           

            if t[i].x < lowestX then

                 

                  lowestElement = i

            end

      end

      return lowestElement

end

 

local lowestX = findLowest(myTable)

 

[/lua]

 

You probably don’t want to be calling your table ‘Table’ because that table contains some useful functions (i.e. table.sort) that won’t be accessible if you do.

 

 

 

You could either sort the table in order of x:

[lua]

local function sortTable(t)

    function compare(a, b)

        return a.x < b.x

    end

    table.sort(t, compare)

end

sortTable(myTable)

[/lua]

 

Or just loop through all the elements and compare the X values:

 

[lua]

 

local function findLowest (t)

      local lowestX = 9999

      local lowestElement

      for i = 1, #t, 1 do

           

            if t[i].x < lowestX then

                 

                  lowestElement = i

            end

      end

      return lowestElement

end

 

local lowestX = findLowest(myTable)

 

[/lua]

 

You probably don’t want to be calling your table ‘Table’ because that table contains some useful functions (i.e. table.sort) that won’t be accessible if you do.