Your last EDIT was my point exactly

Now you've taken 2 call out out PQR_UnitDistance, that you basically have no control over, which leaves us with:
Function PQR_UnitDistance(var1, var2)
if UnitExists(var1) and not UnitIsDead(var1) then
local x1 , y1 = PQR_UnitInfo(var1)
local x2 , y2 = PQR_UnitInfo(var2)
local w = 100000
local h = 100000
local distance = sqrt(min(x1 - x2, w - (x1 - x2))^2 + min(y1 - y2, h - (y1-y2))^2)
return distance
end
end
-----
Now, i know this is all minor thing's, but i'm used to database optimizing IRL and everything adds up, so here goes.
You declaring to local variables that you're not carrying over to something else, or doing any other internal manipulation too, so i assume it's only 'fot the looks'
local w = 100000
local h = 100000
Delete those and put those values directly in the line
local distance = sqrt(min(x1 - x2, 100000 - (x1 - x2))^2 + min(y1 - y2, 100000 - (y1-y2))^2)
Now for this line itself, it's rather pointless to make distance a local variable for the exact same reasons as stated above, plus the fact that you're declaring distance only to return it in the next line, best option is to do this.
return sqrt(min(x1 - x2, w - (x1 - x2))^2 + min(y1 - y2, h - (y1-y2))^2)
and delete
return distance
Leaving you with
Function PQR_UnitDistance(var1, var2)
if UnitExists(var1) and not UnitIsDead(var1) then
local x1 , y1 = PQR_UnitInfo(var1)
local x2 , y2 = PQR_UnitInfo(var2)
return sqrt(min(x1 - x2, 100000 - (x1 - x2))^2 + min(y1 - y2, 100000 - (y1-y2))^2)
end
end
For your thought's about taking out UnitExists(), i can't say really, i only deal with objects. But a general rule of thumb is: Always ensure you have valid input data