Example 3 - functions

<< Click to Display Table of Contents >>

Navigation:  Introducing ThinBASIC >

Example 3 - functions

 

A little more complex script example.

2 functions, one standard, one recursive.

 

'----------------------------------------------------------------------

 

' Optional TBMain function - if found, it is the first function to be executed

function TBMain()

 ' Traditional BASIC variable declaration

 dim msg   as string

 dim count as long
 

 ' Optional modern BASIC variable declaration (DATATYPE variable) with initialization

 ext N1 = 10

 ext N2 = Factorial(N1)

 

 MsgBox 0, "Factorial of " & N1 & " = " & Format$(N2, "0#")

 MsgBox 0, "I've called a recursive function " & RecursiveExample(1, N1) & " times"

 

 For count = 1 To 64

   msg = msg & "[" & Format$(2^count) & "]"

  If MOD(count,2) = 0 Then

     msg = msg & $crlf

  Else

     msg = msg & " "

  End If    

 Next

 

 MsgBox 0, "From 2^1 to 2 ^ 64:\n" & msg

end function

 

 

'---

' A simple standard function - note it can be declared after the line it is called on

'---

function Factorial(InVal As Number) As Ext

Dim i, r As Ext

 

 r = 1

For i = 2 To InVal

   r = r * i

Next

return r

 

end Function

 

'---

' A recursive function

'---

function RecursiveExample(n As Number, MaxRecurse As Number) As Ext

Dim s As String = Repeat$(10000, "X")

 

INCR n                                          

If n >= MaxRecurse Then                            

  return n                                    

Else                                            

  return RecursiveExample(n, MaxRecurse)      

End If                

 

end Function