LuaSurface.get_closest() is very useful. I'm pretty sure it's orders of magnitude faster than sorting the list of entities on the Lua side, given it would need to constantly query the engine for entity positions and such.
I would very much like to extend this function with an optional "count" parameter. This would allow me to get, say, the 5 closest entities from the given list. Currently I have to do this by getting the closest, finding and removing it from the list, getting the next closest... Or sorting the list myself on the Lua side and taking the first N.
This would, however, be a breaking change as it would change the return type from LuaEntity to LuaEntity[], but this could be mitigated: if "count" parameter is not passed, it returns the single LuaEntity, but if the "count" parameter is passed (even if it is 1!) then an array is returned instead. Alternatively, add LuaSurface.get_n_closest() as a separate function.
"count" parameter for LuaSurface.get_closest
Re: "count" parameter for LuaSurface.get_closest
I would go one step further and add that LuaSurface.sort_by_distance(position, entities) would also be useful.
Now, to the relevant part. Sorting 8000+ items by distance on Lua side naively takes ~500ms. Precomputing the distance takes ~25ms and sorting with precomputed distance takes ~15ms, i.e. 40 ms. total, which is more than 10 times faster than a naive solution!
Note that if you are sorting on Lua side, it is crucial to precompute the distance. My use-case: I'm writing a mod where biters drop biomass on death, so there are tons of it around the turrets. I've also added a tool that collects biomass in a large radius. When the tool is used I'm sorting the items, so that if the player doesn't have enough space in his/her inventory, the closest items are collected first. In a worst-case scenario (20 tiles radius, 100% full with biomass) a single use of the tool may collect more than 8000 items.PFQNiet wrote: Thu Jun 24, 2021 10:18 pm LuaSurface.get_closest() is very useful. I'm pretty sure it's orders of magnitude faster than sorting the list of entities on the Lua side, given it would need to constantly query the engine for entity positions and such.
Now, to the relevant part. Sorting 8000+ items by distance on Lua side naively takes ~500ms. Precomputing the distance takes ~25ms and sorting with precomputed distance takes ~15ms, i.e. 40 ms. total, which is more than 10 times faster than a naive solution!