Hello, first post and new to Nim.
How would one use a variable in place of an identifier when referring to an object?
Example:
type
LinksObj* = object
origiaurl*: string
formated*: string
origurl*: string
var Links = newSeq[LinksObj]()
Links.insert(LinksObj(origiaurl: "none", formated: "none", origurl: "none"), 0)
Links.insert(LinksObj(origiaurl: "some", formated: "some", origurl: "some"), 1)
proc echoid(field: string): string =
for link in Links:
if link.origiaurl == "some":
result = link.field
echo echoid("formated")
echo echoid("origurl")
This produces a problem in 4th line from bottom
I came up with the following solution, but will look into fieldPairs as this method is cumbersome. This is indeed a code fragment IRL there are many more items in the object making separate procs for each unwieldy.
type
LinksObj* = object
origiaurl*: string
formated*: string
origurl*: string
var Links = newSeq[LinksObj]()
Links.insert(LinksObj(origiaurl: "none", formated: "none", origurl: "none"), 0)
Links.insert(LinksObj(origiaurl: "some", formated: "1234", origurl: "5678"), 1)
proc fieldval(link: LinksObj, field: string): string {.discardable.} =
if field == "origiaurl":
return link.origiaurl
elif field == "formated":
return link.formated
elif field == "origurl":
return link.origurl
proc echoid(field: string): string =
for link in Links:
if link.origiaurl == "some":
result = fieldval(link, field)
echo echoid("formated")
echo echoid("origurl")
The new fieldval() with fieldPairs
proc fieldval(link: LinksObj, field: string): string {.discardable.} =
for name, value in link.fieldPairs:
if name == field:
return value