Unexpected result using Operator Assignment with methods causing side effects π€
Snoothy opened this issue Β· comments
I encountered an unexpected result related to Operator assignments and methods which has side effects on the mutable variable on the same instance.
I have tried to make a short example of what I have encountered and some variations thereof:
π Simplified example
π π
ππ₯οΈπ β β‘οΈ computer
π computer β
π
π π₯οΈ π
ποΈπ pointer π’ β¬
οΈ 0
π ππ
β π π
π Scenario A, unexpected result
π Set the instances pointer to 123 (side effect) and increment with 4, expecting 127
pointer β¬
β π π 123 β
π Pointer: 4
π πͺ π€Pointer: π€ π‘ pointer 10 β πͺ β
π Reset pointer
π π 0 β
π Scenario B, works as expected
π Split operations
π π 123 β β‘οΈ ret
pointer β¬
β ret
π Pointer: 127
π πͺ π€Pointer: π€ π‘ pointer 10 β πͺ β
π Reset pointer
π π 0 β
π Scenario C, works as expected
π Similar approach but more elaborate
π π 123 β β pointer β‘οΈ π π β
π Pointer: 127
π πͺ π€Pointer: π€ π‘ pointer 10 β πͺ β
π
β π value π’ β‘οΈ π’ π
value β‘οΈ ποΈ pointer
β©οΈ 4
π
β‘ π value π’ β‘οΈ π’ π
value β‘οΈ ποΈ pointer
β©οΈ 4
π
π
The unexpected result relates to pointer β¬
β π π 123 β
. My assumption is that the πβ mutates the pointer
variable and the Operator Assignment then increments it by 4 resulting in a pointer
of 127.
However, it seems that the Operator Assignment has already copied the value of pointer
before the πβ has been evaluated.
I'm not sure if this is a bug or if I'm misunderstanding the scopes π€
Thanks for bringing this up. I see how this is confusing, but this is the way it is intended to work.
pointer β¬
β π π 123 β
is equivalent to pointer β π π 123 β β‘οΈ pointer
(which is not equivalent to C). Emojicode always evaluates expressions in statements strictly from left to right. The result 123 is correct therefore.
I realize the documentation is pretty vague here when saying "an operator is applied to the value of a variable and another operand and the result of the operation is then stored into the variable" but the last example actually implies this: "finally divided by 3" i β¬
οΈβ 3
. This should probably be clarified in the documentation.
We could consider introducing a right operator assignment tough: π π 123 βββ‘οΈ pointer
, which would do what you want.
Just to clarify, the expression pointer β¬
β π π 123 β
evaluates to 4 not 123. (Pointer (0) + return (4)
)
Reordering the equivalence to π π 123 β β pointer β‘οΈ pointer
would give the desired side effect result of 127
correctly applying changes to pointer
before accessing it for addition.
It might be worth considering changing the right operator assignment to π π 123 βββ‘οΈ π pointer
including π to keep consistency for mutable variables
Sorry, for the confusion. It appears I accidentally wrote 123 above.
Including π would indeed be very reasonable as far as consistency is concerned. I donβt really see the need for a right operator assignment though, as code as in your example is confusing anyway.