lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I don't think this is specifically the reason, while, yes, the reads are done before-hand, the setting doesn't need to be done in the reverse order, which is where my question originated from, 
not to mention that this happens even if you use different variables in the left and right side of the _expression_.
If you take a language like Luau, you can also do the variable swapping, but it does not reverse the order when setting it.

Take the following code as an example:

local a = setmetatable({}, {__newindex = print})
local b = setmetatable({}, {__newindex = print})

a.y, b.z = g, g1

If you run this in Lua 5.1 or any newer versions, it will print the z assignment and then y
While in Luau, it does first y and then z.

On Fri, Apr 28, 2023 at 5:49 AM Ziyao <ziyao@disroot.org> wrote:
On 2023-04-28 16:08, Hive Heap wrote:
> Thanks for the answer, I have another question regarding the order of
> assignments.
>
> If we have a script like this
> `a,b,c = d,e,f`, logically we could assume that this is the equivalent
> of
>
> a = d;
> b = e;
> c = f;
>
> but if we look at the bytecode listing, we see that it assigns the
> globals on the reverse order (c, b, a)
>
> As far as I know, most languages do the expected output, such as c++,
> Java, Python, and even Luau now.
> Is there a specific reason for choosing this behavior?

I guess this has something to do with variables appearing on the both
sides of the assignment.

The documentation [1] says

> If a variable is both assigned and read inside a multiple assignment,
> Lua ensures all reads get the value of the variable before the
> assignment.

Consider following code:

a, b = b, a

which actually does swapping. If it is rewritten as

a = b;
b = a;

the result differs obviously.

--
Ziyao

[1]: https://www.lua.org/manual/5.4/manual.html#3.3