Logical operations chain in Lua

Is this the most efficient way to do this in Lua? Thank!

if X >= 0 and Y >= 0 then
    if X1 <= 960 and Y1 <= 720 then
        someCode()
    else end
else end
+4
source share
2 answers

It is recommended to avoid nested statements if, I would try one check if. The best way to be sure is to profile functions and see what works faster.

-- Be paranoid and use lots of parenthesis:
if ( ( (X >= 0) and (Y >= 0) ) and ( (X1 <= 960) and (Y1 <= 720) ) ) then
    someCode()
end

This is the same, but easier to read. Good code is not only fast, but also easy to read.

local condition1 = ((X >= 0) and (Y >= 0))
local condition2 = ((X1 <= 960) and (Y1 <= 720))

if (condition1 and condition2) then
    someCode()
end
+1
source

You can also use operators to make it a little shorter:

if ((X >= 0 && Y >= 0) && (X1 <= 960 && Y1 <= 920)) then
    someCode()
end

Yowza's answer should also be sufficient if you are looking for readability.

0
source

Source: https://habr.com/ru/post/1540165/


All Articles