While working on my tower defense game I ran into a problem with tables:
To find the farthest enemy on the track I use waypoint numbers and the enemies’ distances to them to get a table somewhat that has:
As the index, the distance between the enemy and the next waypoint
I’d suggest moving away from floating-point indexes, anything that’s not an integer, string or Instance in a table can get messy and weird.
If you really wanna store both the distance and object, consider the format {distance, object} then a simple loop to go through every element to get the highest distance.
Another solution is having two tables, one being [number] = distance then another being [object] = number where the number value in the objects table links to the index of the distance, so finding the distance from the enemy would be Distance[Objects[object]].
If you really wanna stick with this though, here’s a simple bit of code to get the highest distance.
local index
for distance, _ in distances do
if not index or distance > index then
index = distance
end
end
print(index)
print(string.format("The farthest (%i studs away) mob is %s", index, distances[index].Name))
EDIT: In my personal opinion you shouldn’t store the distance at all, calculating distance is very fast and very easy so whenever you actually need to get the highest distance, having a table of all the mobs would be much easier to manage and if anyone were to look at your code (including yourself) it’d be much easier to understand.
local distances = {
[5.12] = "Normal enemy",
[2.41] = "Speedy enemy",
[4.23] = "Boss",
}
local function _get(highest)
local wantedIndex = -math.huge
table.foreach(distances, function(a, _)
table.foreach(distances, function(b, _)
wantedIndex = highest and a > b and a > wantedIndex and a or b > wantedIndex and b or wantedIndex
end)
end)
return wantedIndex
end
print(_get(true))
I have no idea why I didn’t think about storing things in a {distance, object} kind of fashion, thanks a lot! I’ll be trying out that script first as changing the table structure would mean changing a lot of other code, but I’ll definitely switch to your first solution later. Thanks again!