Add [] operator for dictionaries

This commit is contained in:
Emery Hemingway 2021-09-23 14:29:16 +02:00
parent 9f2921d0ca
commit cd5dd7dd03
1 changed files with 10 additions and 1 deletions

View File

@ -175,11 +175,20 @@ proc hash*(pr: Preserve): Hash =
!$h
proc `[]`*(pr: Preserve; i: int): Preserve =
## Select an indexed value from `pr`.
## Select an indexed value from ``pr``.
## Only valid for records and sequences.
case pr.kind
of pkRecord: pr.record[i]
of pkSequence: pr.sequence[i]
else:
raise newException(ValueError, "`Preserves value is not indexable")
proc `[]`*(pr, key: Preserve): Preserve =
## Select a dictionary value from ``pr``.
if pr.kind == pkDictionary:
for (k, v) in pr.dict:
if key == k: return v
raise newException(KeyError, "Key not in Preserves dictionary")
else:
raise newException(ValueError, "`[]` is not valid for " & $pr.kind)