Search code examples
functionforward-declarationmaxscript

Maxscript function forward declaration


I'm having the age old problem of Maxscripts not working the first time they are run (from a cold start) because the functions need to be declared before they are used.

The following script will fail the FIRST time it is run:

fOne()
function fOne = 
(
    fTwo()
)

function fTwo = 
(
    messageBox ("Hello world!")
)

We get the error : "Type error: Call needs function or class, got: undefined". Second time around, the script will run fine.

However, adding a forward declaration to the script, we no longer get an error. Horrah! BUT the function is no longer called. Boo!

-- declare function names before calling them!
function fOne = ()
function fTwo = ()

fOne()
function fOne = 
(
    fTwo()
)

function fTwo = 
(
    messageBox ("Hello world!")
)

So, how does forward declaration really work in Maxscript?


Solution

  • To my future self: Keep everything local. Declare the section function as a (local) variable. Be aware of whereabouts in the code you define the functions

    ( -- put everything in brackets
    
        (
        -- declare the second function first!
        local funcTwo
    
        -- declare function names before calling them!
        function funcOne = ()
        function funcTwo = ()
    
        funcOne()
    
        function funcOne = 
        (
        funcTwo()
        )
    
        function funcTwo = 
        (
        messageBox ("Hello world")
        )
    )