Visibility of Locals, Functions, Structures, and User-Interface Items in Rollout Code

The ordering of user-interface items and functions and sub-rollouts in a utility is important when referencing other items and rollouts in handler or local function code. Specifically, you can only reference a user-interface item or rollout or function in a handler or other function if that item or rollout or function has been defined earlier in the utility. A recommended ordering can help ensure this:

local variables

structs

user-interface items

nested rollouts

functions

event handlers

In some situations, cross-referencing means there's no way to order definitions and still pre-define everything. To remedy this, MAXScript lets you pre-declare local rollouts and functions, so code that comes before the function or rollout definition will see the correct object. You do this by declaring such rollouts and functions as uninitialized locals. In the following example, there are two rollouts, ro1 and ro2, that each want to reference items within the other. By pre-declaring them as locals in the main utility, this cross-referencing is possible:

Example:

utility foo "name"

(

local ro1, ro2, ... -- declare local rollouts

...

rollout ro1 "name"

(

local ...

checkbox enable ...

on ... do

ro2.enable.checked = false

)

...

rollout ro2 "name1"

(

local ...

checkbox enable ...

on ... do

ro1.enable.checked = true

)

...

)

As a general rule, it is recommended that all local variable names be explicitly declared as locals at their outermost scope. This will prevent any conflicts from occurring if another script has declared the same variable name as a global variable. While functions, structures definitions, and rollouts will always be local to the utility they are defined in (even if they have the same name as a global variable), declaring these as local will ensure the variables are defined, even if the order in which they are defined is changed. Here's an example showing these declarations:

Example:

utility foo "Object Frabulator"

(

-- local variables

local target_obj

-- local functions

local prop_name

-- local rollouts

local setup

fn prop_name obj name =

for c in obj.children do c.name = name + "_" + c.name

checkbutton setup_btn "Setup"

edittext name_box "New name:"

-- use a checkbutton to dynamically control presence of panels

on setup_btn changed state do

if state then addRollout setup else removeRollout setup

on foo close do

removeRollout setup -- always close rollouts

rollout setup "Setup fraber" -- local panel

(

label hello

pickbutton pick_tgt "Pick object"

on pick_tgt picked obj do

(

target_obj = obj -- access utility local

name_box.text = obj.name -- access utility item

prop_name obj obj.name -- call utility local fn

)

)

)