Hi, all! I'm trying to get the first item out of an OrderedTable that was indexed with strings. I'm not sure which is the best way to do it.
My program is reading a set of configuration files and loading the information into a type Target, which is then added to an ordered table using the name of the target as its index. If the user executes a command that takes a target, I want to get the target using the supplied name as the index (just normalized). So far, so good. However, if the user does not specify a target, I want to select the first one that was added to the table.
Here's my types:
type
Config* = object
# ...
targets*: OrderedTable[string, Target]
Target = object
name*, file*, description*: string
sources*: seq[string]
This is the only way I can think of to get the first index:
if opts.target.len == 0:
for target in cfg.targets.keys:
opts.target = target
break
Is there a better way of getting the first index? Or maybe a better way to structure my data that avoids this?
Thanks!
use
iterator pairs[A, B](t: OrderedTable[A, B]): (A, B)
and break-out after first (does "... in insertion order." kind of implies FIFO?) element.So indeed iterating over the keys and stopping after first one makes sense, I think there is no function to retrieve the first added element. And I think I can remember someone asking how to get the n-th. added element, conclusion was to use a loop similar as you do.
Thanks, Stefan. I'd though I was just being silly and missing something obvious. Good to know this is a reasonable solution.
use
iterator pairs[A, B](t: OrderedTable[A, B]): (A, B)
and break-out after first (does "... in insertion order." kind of implies FIFO?) element.
Hi, lucian. That's what I did in the code sample I provided, but I used the keys iterator instead of pairs.