Author Topic: Recursive functions and variable scope  (Read 9568 times)

support

  • Administrator
  • *****
  • Posts: 859
    • Script BASIC Open Source Project
Recursive functions and variable scope
« on: October 08, 2009, 10:42:03 AM »
This example shows calling a function recursively and how to define how variables are created in functions by default. (GLOBAL or LOCAL)

Code: [Select]
FUNCTION PlusMinusOne(arg)
  IF limit < 5 THEN
    limit += 1
    arg += 1
    PRINT arg,"\n"
    PlusMinusOne(arg)
  ELSE IF arg <> 0 THEN
    arg -= 1
    PRINT arg,"\n"
    PlusMinusOne(arg)
  END IF 
  PlusMinusOne = "Done"
END FUNCTION

limit = 0

x = PlusMinusOne(0)

PRINT x,"\n"
PRINTNL
PRINT arg,"\n"
PRINT limit,"\n"

END

C:\scriptbasic\test>recurfunc
1
2
3
4
5
4
3
2
1
0
Done

undef
5

C:\scriptbasic\test>

In this example I define and assign a GLOBAL variable within the function and reference it in main. By default, variables are global unless explicitly declared as LOCAL in SUBs and FUNCTIONs. SB allows switching this functionality so variables are LOCAL by default in functions/subs and you must explicitly declare variables GLOBAL.

Quote from: SB Docs
declare option DefaultLocal

This will mean that all variables inside a function or subroutine following this line will be local unless explicitly declared to be global.

Code: [Select]
FUNCTION PlusMinusOne(arg)
  IF limit < 5 THEN
    limit += 1
    arg += 1
    PRINT arg,"\n"
    PlusMinusOne(arg)
  ELSE IF arg <> 0 THEN
    arg -= 1
    PRINT arg,"\n"
    PlusMinusOne(arg)
  END IF
  funcvar = "Defined/assigned in the function" 
  PlusMinusOne = "Done"
END FUNCTION

limit = 0

x = PlusMinusOne(0)

PRINT x,"\n"
PRINTNL
PRINT arg,"\n"
PRINT funcvar,"\n"
PRINT limit,"\n"

END

C:\scriptbasic\test>recurfunc
1
2
3
4
5
4
3
2
1
0
Done

undef
Defined/assigned in the function
5

Look what happens when we add DECLARE OPTION DefaultLocal as to the top of the above program. Since limit isn't GLOBAL it's no longer STATIC and breaks the function.

C:\scriptbasic\test>rflocal
Done

undef
undef
0

C:\scriptbasic\test>

Okay, lets fix the program by declaring limit GLOBAL.

Code: [Select]
DECLARE OPTION DefaultLocal

FUNCTION PlusMinusOne(arg)
  GLOBAL limit
  IF limit < 5 THEN
    limit += 1
    arg += 1
    PRINT arg,"\n"
    PlusMinusOne(arg)
  ELSE IF arg <> 0 THEN
    arg -= 1
    PRINT arg,"\n"
    PlusMinusOne(arg)
  END IF
  funcvar = "Defined/assigned in the function" 
  PlusMinusOne = "Done"
END FUNCTION

limit = 0

x = PlusMinusOne(0)

PRINT x,"\n"
PRINTNL
PRINT arg,"\n"
PRINT funcvar,"\n"
PRINT limit,"\n"

END

C:\scriptbasic\test>rflocal
1
2
3
4
5
4
3
2
1
0
Done

undef
undef
5

C:\scriptbasic\test>
Script BASIC Project Manager