Introduction #
Both VAR and DAT blocks can be used to define global variables... So what is the difference ?
- DAT variable: global to all instances of an object and all its methods. Can take on any initial value declared with a LONG, WORD, or BYTE pseudo-op.
- VAR variable: local to each instance of an object; global to all its methods. Gets initialized to zero.
A DAT variable will be global to all instances of the object that defines it. In other words, there's only one copy. A change made to a DAT variable by one instance is a change made for all instances. VAR variables are replicated in each instance of the object that defines them. Changes made by one instance have no effect on the same variable in another instance.
For reference there is another type of variable behaviour that we are not including in this article- variables (or parameters) defined inside a function method:
- Method variable: local to the method it's declared in. Initial value is undefined.
Example code snippet #
This code demonstrates two things:
- DAT can be used to count instances of an object.
- Either VAR or DAT can be used to pass data between cogs if those cogs are launched in the same object.
VAR
long countervar
long astack[ 100 ]
long bstack[ 100 ]
DAT
counterdat long 0
PUB Main
CogNew( a, @astack )
CogNew( b, @bstack )
PRI a
countervar++
counterdat++
PRI b
countervar++
counterdat++
Both 'a' and 'b' have access to 'countervar' and 'counterdat', so their values will go up twice as fast as when only one or the other cogs were running.
Best practice #
The best rule for beginners is perhaps : Use VAR, except when you specifically need to use DAT.
Once you've gained experience and are more familiar with Spin it should all become a lot clearer. Use VAR by default and when you need to use DAT it should become obvious.
Resources #
Parallax Propeller 1 Documentation