在Lua中链式使用逻辑操作符

这是在 Lua 中最有效的方法吗?谢谢!

如果 X >= 0 and Y >= 0 then
    如果 X1 <= 960 and Y1 <= 720 then
        someCode()
    else end
else end
点赞
用户1078537
用户1078537

避免使用嵌套的if语句是个好主意,我们可以试着只用一个if做检查。确定更好的方式是对函数进行性能测试,看哪种方式更快。

-- 因为多使用括号可以避免出错:
if ( ( (X >= 0) and (Y >= 0) ) and ( (X1 <= 960) and (Y1 <= 720) ) ) then
    someCode()
end

下面这种方式和上面的代码等价,但阅读更容易。好的代码不仅效率高,而且易于阅读。

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

if (condition1 and condition2) then
    someCode()
end
2014-06-19 18:18:31
用户3256255
用户3256255

您也可以使用运算符来使其稍微变短:

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

如果您在寻求可读性,那么Yowza的答案也足够了。

2014-08-04 02:32:54