Logical Operators in Lua

Advertisements


Following table shows all the logical operators supported by Lua language. Assume variable A holds true and variable B holds false then:

OperatorDescriptionExample
and Called Logical AND operator. If both the operands are non zero then condition becomes true. (A and B) is false.
orCalled Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A or B) is true.
notCalled Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A and B) is true.

Example

Try the following example to understand all the logical operators available in Lua programming language:

a = 5
b = 20

if ( a and b )
then
   print("Line 1 - Condition is true" )
end

if ( a or b )
then
   print("Line 2 - Condition is true" )
end

--lets change the value ofa and b
a = 0
b = 10

if ( a and b )
then
   print("Line 3 - Condition is true" )
else
   print("Line 3 - Condition is not true" )
end

if ( not( a and b) )
then
   print("Line 4 - Condition is true" )
else
   print("Line 3 - Condition is not true" )
end

When you build and execute the above program it produces the following result:

Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is true
Line 3 - Condition is not true


Advertisements
Advertisements