Okay, so this is how i could think to explain it a bit further:

vortizee wrote:I can’t wrap my head around sorting a table constructed like so:

pcs.A = {}

pcs.A[1] = { x, y, id }; pcs.A[2] = { x, y, id }

Code: Select all

```
local pcs = {} -- Nothing weird here, it's a table; the fact it's local or not doesn't mean anything in this example.
pcs.A = {} -- Another table, key is the string 'A', so pcs['A'] would have worked as well
pcs.A[1] = { x, y, id } -- So, the first numeric index of pcs.A has three numeric fields, an x and y coordinate, probably a number, and an id.
```

vortizee wrote:— values inside those brackets used to place a piece on a map at coordinates pcs.A*[1], pcs.A**[2].*

I'm guessing you mean that the coordinates are inside them, as you defined it before:

Code: Select all

```
local i = 1 -- for example
-- this is how the coords could be accessed.
local xcoord, ycoord = pcs.A[i][1], pcs.A[i][2] -- since, you know, you defined numeric indices inside pcs.A[i], not string ones ('x', 'y')
```

So far probably no issues at all, i just felt i needed to clear up everything.

So, airstruck's sort function would work nicely at sorting the tables indexed by

**i** in

**pcs.A** (pcs.A

* where i = 1 to #pcs.A).*

**table.sort** takes for its parameters the table it needs to sort, which is **pcs.A** at the moment, and a sorting function that is consistent at ordering elements, and works on two at a time; **a** and **b** in the given code example.

When called, **table.sort** internally calls that sorting function with elements from **pcs.A**; whether it's consecutive in order or not, i don't know and frankly don't care, the point is it should sort the table.

A visual aid of sorts: Code: Select all

```
local sorting_function = function (a, b) return kwikDist(a[1], a[2], xo, yo) < kwikDist(b[1], b[2], xo, yo) end
table.sort(pcs.A, sorting_function)
-- let's say we have 3 elements in the table: (7,9), (4,2), (1,3); and our xo and yo are (0,0).
-- first iteration of table.sort: (4,2), (7,9), (1,3) -- compared 1st and 2nd
-- second iteration: (1,3), (7,9), (4,2) -- compared 1st and 3rd
-- third iteration: (1,3), (4,2), (7,9) -- compared 2nd and 3rd
```

Now my math may be wrong with the euclidean distances of such points, but to my eyes, they look sorted.

Edit:

Because I still don’t understand why the sort knows that ‘a' refers to { pcs.A[1][1], pcs.A[1][2] } and ‘b' to { pcs.A[2][1], pcs.A[2][2] }, and not, say, pcs.A[1][3], pcs.A[2][3].

No. The sort goes over the table you give it, a and b will be filled with the elements the sort puts in those variables so that it can sort all the elements. It's not your job to know how the two parameters of -any given- sorting function, or even the builtin one, works. And it's not the job of the sorting function supplied either, it just gets two elements at a time, and it orders only those two. From its perspective, he has a simple job.