type
TPerson = object of TObject
name: string
age: int
# if I remove the discardable pragma here
proc initTPerson(name: string, age: int, obj: var TPerson) {.discardable.} =
obj.name = name
obj.age = age
proc initTPerson(name: string, age: int) : TPerson =
# the following line fails compilation (even with the discard keyword) with
# Error: expression initTPerson(name, age, result) has no type (or is ambiguos)
# With the discardable pragma it compiles
initTPerson(name, age, result)
var
person = initTPerson("Heisenberg", 33)
echo person.age
I am unable to find out why this is happening. Any help here would be greatly appreciated.
The reason I'm trying to do this is so that child class constructors can then call the first initTPerson with an object and get super like behavior. Generation can then be moved into a template (maybe called constructor heh) which will generate the first form automatically when provided with the second form (and its body).
Thanks guys. As Ive said before any help will be appreciated.
I removed the discardable pragma and the example compiles fine for me on osx with 0.9.4 and 0.9.5 404ada2aff51517c56f8beb5735b27a12d3f2485. For style reasons I prefer the var prameter to be first, though:
type
TPerson = object of TObject
name: string
age: int
proc initTPerson(obj: var TPerson, name: string, age: int) =
obj.name = name
obj.age = age
proc initTPerson(name: string, age: int) : TPerson =
result.initTPerson(name, age)
var
person = initTPerson("Heisenberg", 33)
echo person.age
Much of Nimrod code chains procs like this, I'd be surprised if they would not compile. Maybe you should report this as a bug detailing your platform, version and compiler.Yes, compiles and works fine with discardable pragma removed.
$ nimrod -v Nimrod Compiler Version 0.9.5 (2014-07-13) [Linux: amd64]
@gradha: Thanks :) your example compiled for me. My incorrect use of "discard" with a function that does not return anything in the offending line was causing the error (which is probably why the discardable pragma fixed the problem) . I would never have guessed. The program works as expected now :)
@demos: Your idea seems like exactly the thing I want to accomplish. However, I tried the following code and received this error: type mismatch: got (TPerson) but expected 'TStudent'. (line 14, char 24) Am I doing something incorrectly?
type
TPerson = object of TObject
name: string
age: int
TStudent = object of TPerson
id: int
proc initTPerson(name: string, age: int) : TPerson =
result.name = name
result.age = age
proc initTStudent(name: string, age: int, id: int) : TStudent =
# the following line raises the error
result = initTPerson(name, age)
result.id = id
var
student = initTStudent("Ajit Singh", 32, 44)
person = initTPerson("Heisenberg", 33)
echo student.id
echo student.name
echo person.age