jannone
jannone

Reputation: 41

Chaining Logical Operations in Lua

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

if X >= 0 and Y >= 0 then
    if X1 <= 960 and Y1 <= 720 then
        someCode()
    else end
else end

Upvotes: 4

Views: 922

Answers (2)

Moffee
Moffee

Reputation: 411

You can also use operators to make it a tad bit shorter:

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

The answer by Yowza should also suffice tho, if you're looking for readability.

Upvotes: 0

Jose Llausas
Jose Llausas

Reputation: 3406

It is a good idea to avoid nested if statements, I would try a single if check. The best way to be sure is to profile the 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 easy to read.

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

if (condition1 and condition2) then
    someCode()
end

Upvotes: 1

Related Questions