table to calculate and sort closest position

Lets jump right in,

I am trying to get a character in my game to move towards the closest of a few possible positions.

I figured I could create a table and store in each index the calculation for distance. It would look something like this

local closestSpot = { [1] = math.sqrt(( deltaX1 \* deltaX1 ) + ( deltaY1 \* deltaY1 )), [2] = math.sqrt(( deltaX2 \* deltaX2 ) + ( deltaY2 \* deltaY2 )), [3] = math.sqrt(( deltaX3 \* deltaX3 ) + ( deltaY3 \* deltaY3 )), }

(all the delta variable values are calculated outside the table).

Then, I was searching through the API library and found the table.sort() function.

this seems to indicate that I can then sort the values of the above mentioned table in ascending order which would put the lowest value (closest position) into closestSpot[1]

then I could use my transition function to indicate that the player moves to the coordinates indicated by closestSpot[1]

Just wanted to run this by the community to see if this is a valid way of achieving this, or if someone has come up with a better solution.

Thanks

I don’t want to assume anything about your usecase, but from what you’ve said above, it would seem you are looking to implement pathfinding logic. If this is incorrect, please disregard the below.

If it is the case, I suggest looking over Roland Yonaba’s Jumper library. It’s pretty great, and I fork that includes a standalone project that demonstrates the library’s implementation in Corona SDK.

https://github.com/pancinteractive/Jumper 

Thanks for the reference, but I noticed that seems to be in regards to a grid system, which would not be what im in need of

Ironically I just answered a question about table.sort()… since you’re just using numbers, the example in the docs is all you need:

local function compare( a, b ) &nbsp;&nbsp;&nbsp; return a \< b end table.sort( closestSpot, compare )

or something like that. Afterwards closestSpot[1] will be your closest value.

Rob

I don’t want to assume anything about your usecase, but from what you’ve said above, it would seem you are looking to implement pathfinding logic. If this is incorrect, please disregard the below.

If it is the case, I suggest looking over Roland Yonaba’s Jumper library. It’s pretty great, and I fork that includes a standalone project that demonstrates the library’s implementation in Corona SDK.

https://github.com/pancinteractive/Jumper 

Thanks for the reference, but I noticed that seems to be in regards to a grid system, which would not be what im in need of

Ironically I just answered a question about table.sort()… since you’re just using numbers, the example in the docs is all you need:

local function compare( a, b ) &nbsp;&nbsp;&nbsp; return a \< b end table.sort( closestSpot, compare )

or something like that. Afterwards closestSpot[1] will be your closest value.

Rob