A more complex example, this is a snippet from my scrolling map script:
function sort_pairs(list, order_given)
-- collect the keys
local keys = {}
for k in pairs(list) do keys[#keys+1] = k end
if order_given then
table.sort(keys, function(a,b) return order_given(list, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], list[keys[i]]
end
end
end
function big_escape_map_plot_enemies (x, y, xscale)
local Px, Pz = g_PlayerPosX, g_PlayerPosZ
-- player arrow is not centrally located in map so we need
-- to work out edges of bezel in each direction
local xmin, xmax = Px - 1800, Px + 731 / xscale
local zmin, zmax = Pz - 840, Pz + 1400
local enemy_list = {}
for k, v in pairs(ai_soldier_state) do
if v ~= nil and
g_Entity[k] ~= nil and
g_Entity[k]['health'] > 0 and
GetEntityVisibility(k) == 1 then
local Ex, Ez = g_Entity[k]['x'], g_Entity[k]['z']
if Ex > xmin and Ex < xmax and Ez > zmin and Ez < zmax then
-- within bezel so lets add it to the list
enemy_list[k] = {x = Ex, z = Ez}
end
end
end
...
if enemy_list ~= nil then
-- sort on distance from player
local sorted_enemy_list = {}
local xdiff, zdiff
for k, _ in pairs(enemy_list) do
xdiff = math.abs(enemy_list[k].x - Px)
zdiff = math.abs(enemy_list[k].z - Pz)
local rng_sqrd = xdiff*xdiff + zdiff*zdiff
sorted_enemy_list[k] = rng_sqrd
end
for k, _ in sort_pairs(sorted_enemy_list, function(list,a,b) return list[a] < list[b] end) do
if sprite_index < max_enemies then
sprite_index = sprite_index + 1
else
break
end
SetSpritePosition (sprites[sprite_index],
x + ((enemy_list[k].x - Px) / step * xscale),
y - (enemy_list[k].z - Pz) / step);
if ai_soldier_state[k] ~= 'alerted' and
ai_soldier_state[k] ~= 'combat' then
-- Sort of neutral greeny blue colour
SetSpriteColor (sprites[sprite_index], 80, 200, 200, 255)
else
-- Bright red
SetSpriteColor (sprites[sprite_index], 255, 0, 0, 255)
end
end
end
...
It's part of the code that displays enemies and objective on the scrolling map display.
Been there, done that, got all the T-Shirts!