View Single Post
10-26-14, 06:09 PM   #4
mekasha
A Defias Bandit
Join Date: Oct 2014
Posts: 2
That is quite helpful. I understand how the table.sort is working, and how you populate the initial table, but I'm having a lot of trouble adding subsequent items to the table.

I'm especially having trouble getting it to work since I'll have 4 values per line in the table, and almost every example I've come across just shows how to handle a key and single value.

I'm assuming that using my initial code, I'll be changing each Print to some method of inserting a new row into my table, then doing the sort at the end, then printing the sorted table.

edit: I think I have it working, here is my concept code:

Lua Code:
  1. local coords = {}
  2.  
  3. table.insert (coords , {34132, 70.5, 63.5, "scout"})
  4. table.insert (coords , {34931, 21.7, 50.8, "warrior"})
  5. table.insert (coords , {34133, 26.9, 31.9, "hunter"})
  6. table.insert (coords , {34134, 1000, 1000, "unknown location"})
  7.  
  8.  local playerX = 2
  9.  local playerY = 1
  10.  
  11.     table.sort(coords, function(a, b)
  12.       return ((a[2] - playerX)^2 + (a[3] - playerY)^2) > ((b[2] - playerX)^2 + (b[3] - playerY)^2)
  13.     end)
  14.  
  15.     for i,line in ipairs(coords) do
  16.       print(line[1], line[2], line[3], "npc", line[4], "near place")
  17.     end

Is the "for ipairs" the best way for printing out my sorted table? Also, for the items I do not have the coordinates for, is there a more elegant method than setting their coordinates to 1000, 1000?

Last edited by mekasha : 10-26-14 at 06:26 PM.
  Reply With Quote