Hi, I need a help with properties. Why setter isn't call? Also how to set property "title" to readonly state (disable setter)?
type
Info* = ref object of RootObj
level: int
title: string
proc `level=`*(info: var Info, level: int) {.inline.} =
info.level = level
info.title = "Level " & $(level)
var info: Info
new info
info.level = 5
echo info.title
In the same module you can do: info.`level=`(5)
From another module, if the level field is private, you can just do info.level = 5.
r3d, the source of your problem is obviously that your setter proc has exactly the same name as a member field.
def, maybe you should add your above info to manual.
I had the feeling that this variant would work:
type
Info* = ref object of RootObj
level: string
title: string
proc `level=`*(info: var Info, level: int) =
info.level = $level
info.title = "Level " & $(level)
var info: Info
new info
info.level = 5
echo info.title
But still setter proc has no priority:
h.nim(13, 12) Error: type mismatch: got (int literal(5)) but expected 'string'
Yep, but host and h are both fields of Socket, no? (Perhaps I do not fully understand procedural programming for the present, I'm used to OOP only defore). Ok, it is works: main.nim:
import InfoModule
var info: Info
new info
info.level = 5
# info.title = "smth title..." # error, because read only access
echo info.title
InfoModule.nim
type
Info* = ref object of RootObj
level: int
title: string
proc `level=`*(info: var Info, value: int) {.inline.} =
info.level = value
info.title = "Level " & $(value)
proc `title`*(info: var Info): string {.inline.} =
info.title
I think, that would be cool if behavior of properties will be more detailed examined in manual. Especially differents behavior inside and outside of the source module :) Thank you all for your help!Yep, but host and h are both fields of Socket, no?
No. In example in manual Socket datatype has only field h. Getter and setter procs host() and host= are ordinary procs which do access field h. The proc name notation "host=" is only syntactic sugar for making using it easier, as it looks like plain assignment.
The manual suggest adding the F (field) prefix for properties to use with getter/setter: https://nim-lang.org/docs/manual.html#procedures-properties
type
Info* = ref object of RootObj
Flevel: int
Ftitle: string
proc `level=`*(info: var Info, level: int) {.inline.} =
info.Flevel = level
info.Ftitle = "Level " & $(level)
var info: Info
new info
info.level = 5
echo info.Ftitle