Hi I'm trying to modify an object from the outside through another object.
The reason for this is that I'd like a tween object to tween the variables of a target object. How would I achieve this?
Example code:
type Entity = ref object
rotation: int
type Tweener = ref object
target: var int
proc applyTween(t: Tweener, newValue: int) =
t.target = newValue
var e = new Entity
var t = Tweener(target: e.rotation) # Error: invalid type: 'var int' in this context: 'Tweener' for var
t.applyTween(20)
echo "Entity(" & $e.rotation & ")" # Should output "Entity(20)"
Playground link: https://play.nim-lang.org/#ix=4MzG
I was thinking of using the var keyword, as my understanding of it is that it is similar to a pointer. However I am unable to get it working.
This is the only way I know how to get the behavior you want, but I'm sure someone knows better.
type Entity = ref object of RootObj
rotation: int
type Tweener = ref object of RootObj
target: ptr int
proc applyTween(t: Tweener, newValue: int) =
t.target[] = newValue
var e = new Entity
var t = Tweener(target: e.rotation.addr)
t.applyTween(20)
echo "Entity(" & $e.rotation & ")" # Should output "Entity(20)"
From what I understand var in Nim just communicates mutability, it does not necessarily mean a pointer everywhere in the code gen. Ref on the other hand is a traced pointer.