Add recipe for approximating dynamic fields of heterogeneous types like in Python

This commit is contained in:
Mamy André-Ratsimbazafy 2019-11-12 15:22:12 +01:00
parent 264cc90d22
commit 9ff1e441ab
No known key found for this signature in database
GPG Key ID: 7B88AD1FE79492E1
1 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,38 @@
# Context
# https://forum.nim-lang.org/t/5000#31345
#
# The goal is to approximate the dynamic creation of properties
# we use Nim dot operators for that and store everything in a Json object.
import json
{.experimental: "dotOperators".}
type
Action = ref object
properties: JsonNode
template `.`(action: Action, field: untyped): untyped =
action.properties[astToStr(field)]
template `.=`(action: Action, field, value: untyped): untyped =
action.properties[astToStr(field)] = %value
# Our main object, the fields are dynamic
var a = Action(
properties: %*{
"layer": 0,
"add": true,
"vis": false,
"new_name": "fancy_name"
}
)
# And usage, those are not real fields but there is no difference in syntax
echo a.new_name # "fancy_name"
a.algo = 10
echo a.algo # 10