This is a boiled down test from another thread about using the pegs module at compile time. I thought I would throw this out there since there seems to be some general CTFE interest going on right now. I poked around in the VM code to see if I could figure out why the inherited type initialization doesn't work, but I wasn't successful in the (small) amount of time that I spent on it.
# test of initializing inherited types in VM
type
SomeBaseObj {.inheritable.} = object of RootObj
txt : string
InheritedFromBase = object of SomeBaseObj
other : string
proc initBase(sbo: var SomeBaseObj) =
sbo.txt = "Initialized string from base"
proc initInherited(ifb: var InheritedFromBase) =
ifb.txt = "Initialized string from inherited"
static:
var bo: SomeBaseObj
initBase(bo)
doAssert(bo.txt == "Initialized string from base")
var ifb1: InheritedFromBase
initInherited(ifb1)
doAssert(ifb1.txt == "Initialized string from inherited")
var ifb2: InheritedFromBase
initBase(SomeBaseObj(ifb2))
# This assertion passes because ifb2 gets re-initialized
doAssert(ifb2.txt == "")
echo "Done"
By the way, this is now working properly on devel builds.
# test of initializing inherited types in VM
type
SomeBaseObj {.inheritable.} = object of RootObj
txt : string
InheritedFromBase = object of SomeBaseObj
other : string
proc initBase(sbo: var SomeBaseObj) =
sbo.txt = "Initialized string from base"
proc initInherited(ifb: var InheritedFromBase) =
ifb.txt = "Initialized string from inherited"
static:
var bo: SomeBaseObj
initBase(bo)
doAssert(bo.txt == "Initialized string from base")
var ifb1: InheritedFromBase
initInherited(ifb1)
doAssert(ifb1.txt == "Initialized string from inherited")
var ifb2: InheritedFromBase
initBase(SomeBaseObj(ifb2))
# This assertion now passes because ifb2 does not get re-initialized
echo ifb2.txt
doAssert(ifb2.txt == "Initialized string from base")
echo "Done"