berry-lang / berry

A ultra-lightweight embedded scripting language optimized for microcontrollers.
https://berry-lang.github.io
MIT License
782 stars 95 forks source link

Support `..` shorthand for ranges with increment #393

Closed sean-niemann closed 1 month ago

sean-niemann commented 5 months ago

The addition of range increments was a nice touch, although it does not seem to work with the .. shorthand. For simple ranges, we can write

for n : 0..9
  print(n)
end

However, with increments it seems that the range keyword is always needed. It would be nice to allow the .. shorthand for increments as well. eg:

for n : 0..9..3 # range(0, 9, 3)
  print(n)
end
s-hadinger commented 5 months ago

I'm not sure that the syntax 0..9..3 is intuitive enough. Using range with a specific increment is rare enough so using an explicit syntax with range() may not be a bad thing.

Actually I tend to avoid ranges at all in loops because it creates a new object. When using lots of loops, you end up adding pressure on the GC.

I often do (to take your example):

var i = 0
while i < 9
  print(n)
  i += 3
end

Not using a range is also good if you want to iterate over a list and potentially remove some elements (you can't do that with a range):

var mylist = [1, 2, "a", nil, true]

# remove any 
var i = 0
while i < size(mylist)
  if mylist[i] == nil
    mylist.remove(i)   # don't increment i
  else
    i += 1
  end
end

# mylist is now: [1, 2, 'a', true]
s-hadinger commented 1 month ago

Closing since there was no follow-up