I found this bubblesort code here and wonder why it works.
function bubbleSort(A)
local itemCount=#A
local hasChanged
repeat
hasChanged = false
itemCount=itemCount - 1
for i = 1, itemCount do
if A[i] > A[i + 1] then
A[i], A[i + 1] = A[i + 1], A[i]
hasChanged = true
end
end
until hasChanged == false
end
I assumed following :
A[i], A[i + 1] = A[i + 1], A[i]
is the same as:
A[i] = A[i + 1]
A[i + 1] = A[i]
This would lead to
A[i] = A[i + 1]
example
A = { [1] = 3, [2] = 1 }
Would end in
A = { [1] = 1 , [2] = 1 }
Why it does not?
As you are aware, you assumed wrong. As you probably know, in lua, an expression is allowed to return multiple values. In turn, you are also allowed to assign the result of an expression to multiple variables. In your snippet:
A[i], A[i + 1] = A[i + 1], A[i]
The result of A[i+1], A[i]
is evaluated before any value actually changes, witch means when the assignment happens, the values that were in A[i+1], A[i]
are assigned to A[i], A[i+1]
, just as intended.
In short: first, the expression on the right side is evaluated, and only then the assignment itself happens.