Small Basic: How to Simulate Parameters
Let's start with what a function called Add() would look like in VB:
' Call it:
msgbox Add( 5, 6 )
' The function itself:
Function Add( ByVal x as Integer, ByVal y as Integer )
Return x + y
End Function
The way to simulate parameters is to use a stack. That way functions can safely be called recursively, if need be.
Small Basic has a built-in Stack class with methods PushValue and PopValue. You can have multiple stacks, if you want. If we call our stack "p" (p for parameter), then to push and pop values, the syntax would look like this:
Stack.PushValue( "p", 1 )
Stack.PushValue( "p", 2 )
Stack.PushValue( "p", 3 )
TextWindow.WriteLine( Stack.PopValue( "p" ) )
TextWindow.WriteLine( Stack.PopValue( "p" ) )
TextWindow.WriteLine( Stack.PopValue( "p" ) )
The above will print: 3 2 1
Note that a Stack is LIFO (Last In First Out), so things pop out in the reverse order as you push them.
Back to our Add() function. Note that the function has two parameters x and y. So what we do is create a Subroutine called Add, and before calling it, push the two parameters on the stack, in reverse order. Like so:
Stack.PushValue( "p", 6 )
Stack.PushValue( "p", 5 )
Add()
Then, within the Add Subroutine, when we call Stack.PopValue we get the first parameter. The second time we call Stack.PopValue, we get the second parameter, and so on.
So the VB expression:
x + y
Would translate into:
Stack.PopValue( "p" ) + Stack.PopValue( "p" )
Now, how do you simulate a return value. We can decide, by convention, that the return value from a Subroutine is Pushed to the stack before exiting the Subroutine, and the caller of the Subroutine needs to Pop the value to get the return value. So calling our Add Subroutine, and printing out the result would end up looking like this:
Stack.PushValue( "p", 6 )
Stack.PushValue( "p", 5 )
Add()
TextWindow.WriteLine( Stack.PopValue( "p" ) )
and the Add Subroutine would look like this:
Sub Add
Stack.PushValue( Stack.PopValue( "p" ) + Stack.PopValue( "p" ) )
End Sub
So that's how you can simulate parameters in Small Basic.
To simulate Local Variables, see Small Basic: How to Simulate Local Variables.
By Kenny Kasajian http://kasajian.com