Help with sorting entities into a table by distance.

Hello fine and dandy people of facepunch. I am looking for a solution to sorting entities into a table by distance quickly.
I know this is the place for discussing about glua, but I figure that since starfallex is close enough to glua, I can ask here anyways.
You see, the reason I want it done fast is because I’m trying to do this in starfallex, which is a chip and as such, has a quota. So that’s why I need to do it quickly.
A lua solution can be given and I should be able to translate it into starfallex easy enough. Thanks in advance!
P.S. I am using ents.FindInSphere() (or find.inSphere() in SF) to get the ents to sort. My quota is 4 milliseconds.

Does your programming of “not lua” let you call a table sorting function that takes a lambda argument?

Alternatively you might try storing in a container type that auto-sorts for iterators. For example, a C++ map of distance keys and vectors of ents (for index collision resolution) for values would already be sorted.

[editline]7th March 2017[/editline]

Then again, the map would need constant recreation whenever distances change, so if your objects are not always stationary the container method won’t work.


Fixed a few errors in this post.

Uh, im not certain what you mean by a lambda argument, but I would assume so since it has most functions lua has with very similar names. C++ is out of the question, sorry.

local entities = {}

for k, v in pairs(ents.FindInSphere()) do entities[v:GetPos():DistToSqr(LocalPlayer():GetPos())] = v end

local pos = Vector(0,0,0)
table.sort(entities, function(a,b) return a:GetPos():DistToSqr(pos) < b:GetPos():DistToSqr(pos) end)