Swap the Values of Two Variables in PlayBasic
How To Swap the Values of Two Variables in PlayBasic
PlayBasic has many useful functions. Unlike most BASIC dialects, PlayBasic has a simple way to swap the values of two variables, and more than one function to do it. But first, for the sake of completeness, here's the hard way first.
The Hard Way
Create a 'Temporary' Variable
To swap the values of two variables, you're going to need a third variable. Declare it along with your other variables :
ForceDeclaration
Declaration
tempVar, var1, var2
EndDeclaration
Swap Out the Values of the Variables
First, make sure you put the value of the first variable in the "temporary" variable.
tempVar = var1
Then, change the first value to the value of the second variable.
var1 = var2
Finally, change the value of the second variable to the "temporary" variable.
var2 = tempVar
Complete Code
ForceDeclaration
Declaration
tempVar, var1, var2
EndDeclaration
var1 = 1
var2 = 2
tempVar = var1
var1 = var2
var2 = temp
Print "Var1 : " + str$(var1)
Print "Var2 : " + str$(var2)
Sync
WaitKey
Swapping with Swap
If you use the Swap function, you do not need an extra variable.
Swap var1, var2
Complete Code
ForceDeclaration
Declaration
var1, var2
EndDeclaration
var1 = 1
var2 = 2
Swap var1, var2
Print "Var1 : " + str$(var1)
Print "Var2 : " + str$(var2)
Sync
WaitKey
page revision: 6, last edited: 15 Jul 2012 02:42