Lua - Operators Precedence



Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example, x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Unary not # - Right to left
Concatenation .. Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Relational < > <= >= == ~=  Left to right
Equality == ~= Left to right
Logical AND and Left to right
Logical OR or Left to right

Example - Arithmetic Operators Precedence

In this example, we're creating three variables a, b and c and a arithmetic statement is written to check operator preference −

main.lua

a = 20
b = 10
c = 15

-- a + b * c == a + 150 == 20 + 150 = 170 
result = a + b * c  
print("a + b * c", result)

Output

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

a + b * c	170

Example - Logical Operators Precedence

In this example, we're creating three variables a, b and c and a logical statement is written to check operator preference −

main.lua

a = 20
b = 10
c = 15

-- a > b and a > c == true and true == true 
result = a > b and a > c  
print("a > b and a > c ", result)

Output

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

a + b * c	170

Example - Precedence of Unary Operator

In this example, we're creating three variables a, b and c and a unary statement is written before logical and statement to check operator preference −

main.lua

a = false
b = true

-- not a == true
-- not a and b == true and true == true
result = not a and b
print("not a and b ", result)

Output

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

not a and b    true
lua_operators.htm
Advertisements