Lua算術運算符

下表列出了所有的Lua語言支持的算術運算符。假設變量A持有10和變量B持有20,則:

運算符

描述

示例

+

兩個操作數相加

A + B = 30

-

從所述的第一個減去第二操作數

A - B = -10

*

兩個操作數相乘

A * B = 200

/

通過分子除以反分子

B / A = 2

%

模運算和整數除法後的餘數

B % A = 0

^

指數運算符需要的指數

A^2 = 100

-

一元運算 - 運算符相當於取反

-A = -10

例子

試試下面的例子就明白了所有的Lua編程語言提供了算術運算符:

a = 21
b = 10
c = a + b
print("Line 1 - Value of c is ", c )
c = a - b
print("Line 2 - Value of c is ", c )
c = a * b
print("Line 3 - Value of c is ", c )
c = a / b
print("Line 4 - Value of c is ", c )
c = a % b
print("Line 5 - Value of c is ", c )
c = a^2
print("Line 6 - Value of c is ", c )
c = -a
print("Line 7 - Value of c is ", c )

當執行上面的程序,它會產生以下結果:

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 441
Line 7 - Value of c is -21