Hello,
i really like OOP macro from https://github.com/jyapayne/nim-extensions. There are so far two problems
Example:
#test_class.nim
import oop
class MyClass:
var
value: int
method init*(value: int){.base.}=
self.value = value
method print{.base.}=
echo self.value
#main.nim
from test_class import MyClass
var m : MyClass;
m = new MyClass(value:111)
m.print()
Compiler reports main.nim(5, 16) Error: the field 'value' is not accessible.
What am i missing? Thanks alot.
I didn't test and never used the oop library but you are probably missing the public export marker *
import oop
class MyClass:
var
value*: int
method init*(value: int){.base.}=
self.value = value
method print*{.base.}=
echo self.value
@sayol, I'm the creator of that library. In order to export the class, you need to put the export marker with of RootObj at the end. This is due to some limitations in the Nim parser.
You also need the export markers on all methods/properties you want to be exported, just as @mratsim suggested.
I've modified your code to work with the latest Nim devel branch.
#test_class.nim
import extensions/oop
class MyClass* of RootObj:
var
value*: int
method init*(value: int) {.base.} =
self.value = value
method print*() {.base.} =
echo self.value
# main.nim
from test_class import MyClass, print # need to import print here in order for the compiler to see it.
# Otherwise, `import test_class` can be used to import all.
var m: MyClass
m = MyClass(value: 111)
m.print()
You need to change your methods from
method init*(value: int) {.base.} =
self.value = value
method print*() {.base.} =
echo self.value
to
method init*(value: int) {.base.} =
self.x = value
method print*() {.base.} =
echo self.x
Ah, sorry. Of course i did change body of init and print to use instance variable x so this part is fine.
Though changing constructor call to m = MyClass(x: 111) doesnt make much of a sense to me. Name of constructor parameter is still value, not x.
@sayol, mratsim is right. The init method's name doesn't matter for the properties. The constructor is generated based on the properties, so if you change it to
class MyClass* of RootObj:
var
x*: int
...
You also need to change the constructor call. Perhaps it would make more sense to generate the properties based on the init method, but that could be argued.