Page 1 of 1

Can I declare and use a function within a function?

Posted: Mon Feb 23, 2009 9:10 pm
by sbass1
Sorry for what is likely a simple question. I searched on "function" before posting but got 4500+ hits, and the Basic doc is unclear. Couldn't find it on Google either.

So...can I declare and use utility functions within a function? What I want to do is something like:

* Declare function (this is the main function)
DEFFUN MyFunction(pInputValue, pInputPattern) Calling "DSU.MyFunction"

* Declare utility function, which is a sub-function in this file
DEFFUN MatchPattern(pInputValue, pInputPattern)

... stuff in MyFunction function

Return(Ans)

* ===== Subroutines =====

Sub1:
If Not(MatchPattern(foo,bar)) Then Return(1)
... stuff
Return(0)

Sub2:
If Not(MatchPattern(bar,foo)) Then Return(1)
... different stuff
Return(0)

* ===== Utility Functions =====

Function MatchPattern(pInputValue, pInputPattern)
... stuff
Return pInputValue Matches pInputPattern

End

This is an oversimplification of what I want to do. I know I can use subroutines - my question is whether I can declare and use additional sub-functions.

Thanks,
Scott

Posted: Mon Feb 23, 2009 9:24 pm
by ray.wurlod
This might be confusing. What do you mean by "in this file"?

If it's a purely internal routine, within the same routine, then it is accessed via a GOSUB statement and no DEFFUN declaration is required.

Otherwise, it's a separate function - has a separate entry in the Routines branch of the repository - and you need a DEFFUN declaration (with a "DSU." prefix in the CALLING clause, which you seem to have missed) to inform the compiler that the name followed by a left parenthesis is that of a function rather than that of a dimensioned array.

Posted: Tue Feb 24, 2009 12:32 am
by sbass1
Hi Ray,

Yes the utility functions would be in the same file.

I guess I'm used to more structured programming languages with variable scoping. I wanted to use the calling syntax of a function so I could use it in an IF statement, and any variables defined in the function would be out of scope when the function ended.

I can make it work using GoSub but IMO it's syntactically messier for what I want to do.

Thanks,
Scott

Posted: Tue Feb 24, 2009 6:05 am
by ray.wurlod
Everything in the same file has global scope within that file. This can result in side effects if you do not take care using GoSub.