Lua 中的四个变量交换如何工作?

How does four variable swapping work in Lua?

你好,我在 lua 中有这个 activity: 将数据输入 4 个不同的变量(A、B、C 和 D)。将 A 的内容放在 C 中,C 的内容放在 B 中,B 的内容放在 D 中,D 的内容放在 A 中。显示新的内容顺序。不要丢失原始数据。 但我不知道该怎么做 你能帮帮我吗?

在 lua 中完成交换值的一种简单方法是使用多个赋值。

Programming in Lua: 4.1 – Assignment

In a multiple assignment, Lua first evaluates all values and only then executes the assignments. Therefore, we can use a multiple assignment to swap two values, as in

 x, y = y, x                -- swap `x' for `y'`

对于你的情况,它看起来像这样:

a, b, c, d = d, c, a, b

您还可以在 Lua 参考手册中找到类似的信息

Lua Reference Manual: 3.3.3 – Assignment:

The assignment statement first evaluates all its expressions and only then the assignments are performed. Thus the code

    i = 3
    i, a[i] = i+1, 20

sets a[3] to 20, without affecting a[4] because the i in a[i] is evaluated (to 3) before it is assigned 4. Similarly, the line

    x, y = y, x

exchanges the values of x and y, and

    x, y, z = y, z, x

cyclically permutes the values of x, y, and z.


如果您是 lua 的新手,这本书 Programming in Lua 是此类项目的绝佳资源。我鼓励您阅读它,这是一本写得很好的 lua.

指南