官术网_书友最值得收藏!

Arithmetic operators

Arithmetic operators do math; these operators work on numbers to perform addition, subtraction, multiplication, and division. Operators to find the remainder of a division, negate a number, or raise a number to a power are also available in Lua. The negation operator uses a minus sign and is a unary operator; otherwise, all other arithmetic operators are binary operators (that is, they work on two operands).

The addition operator (+) adds two operands together:

x = 7 + 10
y = x + 3
z = x + y

The subtraction operator (-) will subtract the second operand from the first:

x = 8 - 3
y = 10 - x
z = x - y

The multiplication operator (*) will multiply the given operands:

x = 2 * 2
y = x * 3
z = x * y

The division operator (/) will divide the numerator (first operand) by the denominator (second operand):

x = 20 / 10
y = 5 / x
z = x / y

The modulus operator (%) returns the remainder of an integer division. This means both the numerator (first operand) and denominator (second operand) are cast to be integers, divided, and the result is returned. Numbers are cast to integers, not rounded. This means that any decimal numbers are discarded, so 5.1, 5.5, and 5.9 would all simply become 5. Here is an example:

x = 5 % 2 -- result is 1
y = 5.7 % 2 -- 5.7 is treated as 5, result is 1.
z = 5.3 % 2.9 -- result is 1
Why is the result of 5 % 2 simply 1? Two divides into five evenly twice, with a remainder of 1. The modulus operator returns the remainder of this division.

The negation operator (-) negates a number. This is the only unary arithmetic operator. Here is an example:

x = -5 -- x = -5
y = -x -- y = 5
y = -y -- y = -5

The exponent operator (^) will take the base (first operand) and raise it to the power of the exponent (second operand):

x = 10 ^ 2
y = x ^ 2
z = 3 ^ 3
Lua only offers partial support for the exponent operator. An explanation of why this decision was made is available online at  https://www.lua.org/pil/3.1.html.
主站蜘蛛池模板: 瓦房店市| 冀州市| 台州市| 澄城县| 象州县| 衡阳县| 黎城县| 宽城| 阿合奇县| 湾仔区| 沙坪坝区| 灵宝市| 康平县| 广南县| 伊金霍洛旗| 德惠市| 阿坝县| 汶上县| 和顺县| 凤凰县| 井陉县| 乌什县| 明溪县| 清丰县| 仁寿县| 同仁县| 突泉县| 北安市| 玉环县| 南通市| 阜宁县| 常山县| 黄骅市| 工布江达县| 唐海县| 板桥市| 江川县| 库车县| 城口县| 肃宁县| 南充市|