So, I used nim back before v1, so it has been awhile. I recently started looking at it again now that it has matured a lot.
running through my default language learning program, I ran into this question:
Background I have two objects:
type
Person* = object
name: string
age: int
sex: Sex
type
Family* = object
members: seq[Person]
name: string
the family object contains a sequence of persons, these are in a separate file, and members is not exposed. I would like to be able to run the following code in another file:
for person in family:
echo(person.name)
I understand i can just make the members field public, but I would like to know if there is another way of doing this. Like overwriting the 'in' operator and exposing that or is there a way to set the Family object to use the member field as the iterator? I wrote this to add a member to the family, so it looks like the flexibility is there, just don't know how to implement it.
proc `+`*(f: var Family, p: Person) =
f.members.add(p)
Thanks.
nvm - i wasn't using the iterator items*
iterator items*(f: Family): Person =
var i = 0
while i < f.members.len:
yield f.members[i]
inc i
You can simplify this:
iterator items*(f: Family): Person =
for member in f.members:
yield member
Unfortunately, Nim doesn't have an equivalent of Python's yield from and the aliasing PR didn't get accepted, so this is the best you can do.