Shop OBEX P1 Docs P2 Docs Learn Events
global variables aren't acting very global? — Parallax Forums

global variables aren't acting very global?

stampinatorstampinator Posts: 18
edited 2015-08-16 21:21 in BASIC Stamp
Hi everyone,

I am working on a bs1 program, and am a little confused by the behavior I am getting...

if I do (simplified version of my code):
symbol current = B0
symbol state = B1
symbol lastState = B2
symbol count = B3
symbol switch = B4

main:
current = PINS
state = current & $F
IF count > 0 THEN check
switch = current & $30
if switch = 0 THEN switch_triggered
GOTO main

check:
IF state = lastState THEN main
count = count - 1
GOTO fire

switch_triggered:
count = count + 1
lastState = state
GOTO main

fire:
LET PIN7 = 1
PAUSE 100
LET PIN7 = 0
lastState = 0
GOTO main


Basically what I am experiencing is, state is always different than lastState, even though they should be the same. So, for example, if state is $03, and the switch_triggered method gets called, then I expect lastState to get set to $03, so when the check method gets called, nothing should happen until the state changes again-- to say $7. However, what is actually happening is, as soon as switch_triggered gets called, the fire method gets called even though the state has not changed... I am totally confused by how this is possible, and what is going on. If anyone has any insight or suggestions I'd greatly appreciate it.

Comments

  • Because laststate is not initialized, so the first time through, it is zero, and if state is not zero, then it will call fire. Then in fire, you set laststate to zero again, and the same thing happens. You need to initialize laststate to state the very first time through the program, and not set it to zero in fire.
  • I don't think that was the problem.. My pseudo code might not have illustrated exactly what I was doing. But I was reading the docs, regarding doing:

    foo = 123
    bar = foo

    It said that bar is a reference to foo. So I found that if I actually did lastState = PINS & $F, instead of lastState = state, then it worked.
  • If you say "foo = 123" then "bar = foo", it simply sets foo to the value "123", then copies that value into "bar". There are no references involved. An assignment simply copies the value on the right into the variable on the left.

    I think Sapphire is correct. Pay attention to how the variables are initialized. The default is zero.
Sign In or Register to comment.