Skip to content

Instantly share code, notes, and snippets.

@Vindaar
Created May 24, 2018 21:47
Show Gist options
  • Save Vindaar/dba0158d0b1b52caa0704b0de1e43eb9 to your computer and use it in GitHub Desktop.
Save Vindaar/dba0158d0b1b52caa0704b0de1e43eb9 to your computer and use it in GitHub Desktop.
import macros
type
Container = object
field1: string
field2: string
fieldInt: int
macro setField(obj: untyped, name: string, val: untyped): untyped =
result = newStmtList()
let field = parseExpr(name.strVal)
result.add quote do:
`obj`.`field` = `val`
var h: Container
echo h
# (field1: nil, field2: nil, fieldInt: 0)
h.setField("field1", "it works!")
echo h
# (field1: "it works!", field2: nil, fieldInt: 0)
h.setField("fieldInt", 120)
echo h
# (field1: "it works!", field2: nil, fieldInt: 120)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment