ThakeeNathees / pocketlang

A lightweight, fast embeddable scripting language.
https://thakeenathees.github.io/pocketlang/
MIT License
1.52k stars 80 forks source link

[Enhancement] add iterator protocol for object #282

Open khchen opened 2 years ago

khchen commented 2 years ago

Object can be used as iterator if _next and _value is defined. Similar to wren's iterator protocal. Example 1:

class Countup
  def _init(first, last, step)
    self.first = first
    self.last = last
    self.step = step
  end

  def _next(iter)
    if iter == null then return self.first end
    iter += self.step
    if iter > self.last then iter = null end
    return iter
  end

  def _value(iter)
    return iter
  end
end

for i in Countup(0, 10, 2)
  print(i)
end

Output:

0
2
4
6
8
10

Example 2:

class Node
  def _init(val)
    self.val = val
    self.next = null
  end

  def _str()
    return "(${self.val})"
  end
end

class LinkedList
  def _init()
    self.head = null
  end

  def append(node)
    if self.head == null
      self.head = node
    else
      last = self.head
      while last.next do last = last.next end
      last.next = node
    end
  end

  def _next(iter)
    if iter == null then return self.head end
    return iter.next
  end

  def _value(iter)
    return iter
  end
end

ll = LinkedList()
ll.append(Node(4))
ll.append(Node(6))
ll.append(Node(3))
ll.append(Node(9))

for n in ll
  print(n)
end

Output:

(4)
(6)
(3)
(9)

Example 3:

class StringIter
  def _init(text)
    self.text = text
  end

  def _next(iter)
    if iter == null then return 0 end
    iter += 1
    if iter >= self.text.length then iter = null end
    return iter
  end

  def _value(iter)
    return self.text[iter]
  end
end

for c in StringIter("hello")
  print(c)
end

Output:

h
e
l
l
o