📅  最后修改于: 2020-10-16 05:14:22             🧑  作者: Mango
运算符是一个符号,告诉解释器执行特定的数学或逻辑操作。 Lua语言具有丰富的内置运算符,并提供以下类型的运算符-
本教程将逐一说明算术,关系,逻辑和其他各种运算符。
下表显示了Lua语言支持的所有算术运算运算符。假设变量A持有10,变量B持有20,则-
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B will give 30 |
– | Subtracts second operand from the first | A – B will give -10 |
* | Multiply both operands | A * B will give 200 |
/ | Divide numerator by de-numerator | B / A will give 2 |
% | Modulus Operator and remainder of after an integer division | B % A will give 0 |
^ | Exponent Operator takes the exponents | A^2 will give 100 |
– | Unary – operator acts as negation | -A will give -10 |
下表显示了Lua语言支持的所有关系运算符。假设变量A持有10,变量B持有20,则-
Operator | Description | Example |
---|---|---|
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
~= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. | (A ~= B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
下表显示了Lua语言支持的所有逻辑运算符。假设变量A为真,变量B为假,则-
Operator | Description | Example |
---|---|---|
and | Called Logical AND operator. If both the operands are non zero then condition becomes true. | (A and B) is false. |
or | Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. | (A or B) is true. |
not | Called 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. |
Lua语言支持的其他运算符包括串联和长度。
Operator | Description | Example |
---|---|---|
.. | Concatenates two strings. | a..b where a is “Hello ” and b is “World”, will return “Hello World”. |
# | An unary operator that return the length of the a string or a table. | #”Hello” will return 5 |
运算符优先级确定表达式中术语的分组。这会影响表达式的求值方式。某些运算符具有更高的优先级;例如,乘法运算符的优先级比加法运算符-
例如,x = 7 + 3 * 2;在这里给x分配13,而不是20,因为运算符*的优先级比&plus;的优先级高。因此它首先乘以3 * 2,然后加到7。
在此,优先级最高的运算符出现在表格的顶部,而优先级最低的运算符出现在表格的底部。在表达式中,优先级较高的运算符将首先被评估。
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 |