Function vs Sub as Main()

Quick question, why would you use a Function method instead of Sub when declaring Main()? I see several examples that use Function, but I’m not sure why.

EXAMPLES:

Function Main() 
       initTheme()
End Function

as opposed to

Sub Main()
       initTheme()
End Sub

Thanks
Bud

Do they not do the same thing?

They do, but why change it to a Function for some, but not for others?

I did see on page 20 of the BrightScript reference guide, that a “Function statement are at global scope”, so was wondering if people were declaring them for this reason??

Thanks
Bud

A function expects to return a value, a sub does not. You can use a sub for any chunk of code that you don’t care about the return, or use function without a return value set. I THINK it won’t complain if you have a function without a return value specified in the definition, and you don’t explicitly return. I know at one point if you defined a function with an expected return type, and if you don’t return anything it would error.

e.g.


function dostuff() as integer
    print "I did stuff"
end function

That would result in an error because there was no return statement in the function. Not sure with the current firmware version…

Cool, thanks. I was thinking it was something like that, but when I saw the example on page 21 of the BrightScript reference where it used a Function without a type, I got confused why.

FYI, your example works in 3.0, but the following broke it

Function Main() as integer
    
    print "I do stuff"
    
    return "foo"
    
End Function

It’s kind of less trouble to just use functions for everything, especially as it frequently turns out you need to return a value, saves quite a bit of retyping in the long run.

If there is some reason to use subs in some circumstances, I don’t know what it is.

FYI, you can actually use:

function main()

end function

instead of


sub main()

end sub

which could also be useful in some (rare) situations.

  • Joel

I agree, I find it easier to use functions in all cases. Last time we checked, we didn’t see any appreciative difference between the performance of a sub and a function, so there’s little reason to use subs in my opinion.

Perfect, Functions it is.

Thanks!
Bud

A Sub’s just a Function without a return type. It’s probably more for code readability than actual execution, but it fits the general VB/VBScript syntax that BrightScript is based on. You should note that adding a return type to a Sub declaration will throw an error in 3.0, while it did not in earlier versions of the SDK.