none
Strange variable behavior RRS feed

  • Question

  • I noticed this strange behavior in a program I was writing and this shows what happens:

    S1=1
    S1[1]=2
    TextWindow.Write("S1="+S1+" ")
    TextWindow.WriteLine("S1[1]="+S1[1])
    S1=S1[1]
    TextWindow.Write("S1="+S1+" ")
    TextWindow.WriteLine("S1[1]="+S1[1])

    When you run this you get:

    S1=1=2; S1[1]=2
    S1=2 S1[1]=
    Press any key to continue...

    S1=1=2; is strange in the 1st line, as is S1[1]= in the 2nd line.   I am trying to use the single variable S1 and I also have an array S1.  I guess I can't do that?

    Thanks


    • Edited by Mark J K Wednesday, December 26, 2012 3:03 PM
    Wednesday, December 26, 2012 3:03 PM

Answers

  • Small Basic stores arrays with a key=value combination.  Your "strange" behavior comes from overwriting your data.

    first you assign S1 = 1

    then overwrite that by assigning S1 as an array where key 1 = value 2

    you then print out the entire array S1    "1=2;"    but expected 1 to be printed

    you then print the first index of the S1 array    "2"    that looks correct

    next you overwrite the S1 array changing it to a variable with the value 2

    this makes your next printed statement correct    "S1=2"   

    but now your key 1 in the S1 array no longer exists thus the blank

     
    Wednesday, December 26, 2012 4:25 PM

All replies

  • Small Basic stores arrays with a key=value combination.  Your "strange" behavior comes from overwriting your data.

    first you assign S1 = 1

    then overwrite that by assigning S1 as an array where key 1 = value 2

    you then print out the entire array S1    "1=2;"    but expected 1 to be printed

    you then print the first index of the S1 array    "2"    that looks correct

    next you overwrite the S1 array changing it to a variable with the value 2

    this makes your next printed statement correct    "S1=2"   

    but now your key 1 in the S1 array no longer exists thus the blank

     
    Wednesday, December 26, 2012 4:25 PM
  • Wow, now that makes sense.  Thanks.  I will need to use variables of different names.

    Thanks again.

    Wednesday, December 26, 2012 4:29 PM