Hi,
I try to assign an object proc to a closure variable, but don't know how:
var test: proc(i: int) {.closure.}
test = proc(i: int) = echo i
test(23)
type
TTest = object
x: int
proc callback(a: TTest, i: int) = echo a.x + i
var me: TTest
me.x = 12
test = me.callback # does not compile
test(11)
type
ITest = tuple[
setter: proc(v: int) {.closure.},
getter1: proc(): int {.closure.},
getter2: proc(): int {.closure.}]
proc getInterf(): ITest =
var shared, shared2: int
return (setter: proc (x: int) =
shared = x
shared2 = x + 10,
getter1: proc (): int = result = shared,
getter2: proc (): int = return shared2)
var i = getInterf()
i.setter(56)
echo i.getter1(), " ", i.getter2()
it would have been a nice feature, if closures and object procs where the same, but what I see from the implementation, the environment is the last parameter and in a object proc the "self" is the first. So it's even impossible with a cast.
My solution now is to wrap the callback in a anonymous closure, but this costs another call :(
proc callMeBack(me: TTest): proc(i: int) = return proc(i: int) = callback(me, i)
test = callMeBack(me)
test(12)
@adrianv
IMHO, it's better not to mix closures and objects, either you have an object to store the context for your proc or you have closure environment, not both, for the sake of simplicity.