Discord
Login
Community
DARK THEME

For..in

How to iterate through the list items using the "for..in" loop, then when I want to change the value of a given list item, I can't do it.

Array = class
  constructor = function( size )
    list = []
    for loop = 1 to size
      list.push( 100 + loop )
    end
  end
  div_a = function( value )
    for item in list
      item /= value
    end
  end
  div_b = function( value )
    for item in list
      item = item / value
    end
  end
  div_c = function( value )
    for loop = 0 to list.length - 1
      list[ loop ] /= value
    end
  end
  printList = function()
    local string = ''
    for item in list 
      string += ' , ' + item 
    end
    print( string )
  end
end

init = function()
  array = new Array( 10 )
  array.printList()
  array.div_a(2)
  array.printList()
  array.div_b(2)
  array.printList()
  array.div_c(2)
  array.printList()
end

update = function()
end

draw = function()
end

I'm doing something wrong ??

Number and string types are passed by value and not by reference, so in div_a and div_b you're just changing a local copy of the value, and not the actual value that is in the list.

You'll have to do:

for i=0 to list.length-1 by 1
  list[i] /= value
end

Which is what you did in div_c, and that one is actually working.

If you don't know what I mean by "passed by value/reference", take a look at this video: https://www.youtube.com/watch?v=_5ChjwWwmeE

The video is in Lua, but the logic is the same. In micrscript, lists and objects/classes can be passed by reference. Maybe functions too, but I'm not sure. But numbers and strings are always passed by value.

Also be careful with loops that don't have by 1, because there's a pitfall there.

If the list is empty, this will loop backwards twice:

for loop = 0 to list.length - 1
  list[ loop ] /= value
end

Because list.length-1 will be -1 and it will think you want to do a backwards loop from 0 to -1, because you're not specifying that you want a forward loop. (This isn't documented, unfortunately.)

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community