Operators Precedence in Lua

Advertisements


Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others.

Example

Try the following example to understand all the precedence of operators in Lua programming language:

a = 20
b = 10
c = 15
d = 5

e = (a + b) * c / d;-- ( 30 * 15 ) / 5
print("Value of (a + b) * c / d is   :",e )

e = ((a + b) * c) / d; -- (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is :",e )

e = (a + b) * (c / d);-- (30) * (15/5)
print("Value of (a + b) * (c / d) is :",e )

e = a + (b * c) / d;  -- 20 + (150/5)
print("Value of a + (b * c) / d is   :",e )

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

Value of (a + b) * c / d is   :	90
Value of ((a + b) * c) / d is :	90
Value of (a + b) * (c / d) is :	90
Value of a + (b * c) / d is   :	50


Advertisements
Advertisements