SmallBASIC icon indicating copy to clipboard operation
SmallBASIC copied to clipboard

Maps in an array cannot be updated in for...in loop

Open byronpendason opened this issue 7 months ago • 3 comments

I noticed this odd behaviour when making a game. I had an array of enemies, and iterated through them using a for...in loop, and noticed their x and y values did not change!

So I simplified things to demonstrate the behaviour, and came up with this:

arr = []
for i=1 to 3
  local temp = {}
  temp.x = i
  arr << temp
next

print arr

for M in arr
  M.x += 3
next

print arr

My output:

[{"x":1}, {"x":2},{"x":3}]
[{"x":1}, {"x":2},{"x":3}]

The second line should be [{"x":4},{"x":5},{"x":6}].

byronpendason avatar May 31 '25 16:05 byronpendason

I'm on Android using the app, in case it matters.

byronpendason avatar May 31 '25 16:05 byronpendason

In your example M is a copy of the array element. Changes to M will not change the actual element of the array. At the moment this is the expected behavior of the FOR ... IN loop.

If I want to change elements of the array, I iterate and access the array elements by index.

The FOR ... IN loop is a nice and easy way to iterate through an array. I think it would be great, if the loop element is a pointer to the array element and changes to the loop element will be applied to the array element.

Joe7M avatar May 31 '25 18:05 Joe7M

In your example M is a copy of the array element. Changes to M will not change the actual element of the array. At the moment this is the expected behavior of the FOR ... IN loop.

If I want to change elements of the array, I iterate and access the array elements by index.

The FOR ... IN loop is a nice and easy way to iterate through an array. I think it would be great, if the loop element is a pointer to the array element and changes to the loop element will be applied to the array element.

Thank you so much for your reply and for your help! I had tried doing that, but got a "Not supported" toast notification. I must have done it wrong though because I just tried editing it again, and it worked this time. Lol.

I changed the second loop to this:

for i=0 to len(arr)-1
  arr[i].x += 3
next

Next step is to make the same change to my main game loop in the file I was working on when I originally discovered this behaviour. Thanks once again for your help!

byronpendason avatar May 31 '25 19:05 byronpendason