Notifications
Clear all

[Closed] Call (local) function from external file

Is it possible to call a local(not global) function from external ms file?

5 Replies

Yes, if you can access the object that the function is local to.

a function that is local to an instantiated struct ,
or local to a rollout dialog,
or that local custom attribute
can be called.

--executed in script editor, this is global
fn globalFn=(print"hello world")
globalFn() --prints "helloWorld"

--you can access a fn local to an instantiated struct
struct myStruct(
	fn myFn =(print "my function in a struct")
)
myStructinstance=myStruct()
myStructinstance.myFn()--prints "my function in a struct"

--you can access a fn local to a created dialog 

dialog = rollout dialog "Dialog"
	(
		fn myFn =(print "my function in a rollout")
		label l1 "i have a local function"	
	)
createdialog dialog
	
dialog.myfn()--print "my function in a rollout"
	
--executed in script editor, this is local and cannot be accessed 
(
	fn localFn=(print"hello world")
)
localFn() -- Type error: Call needs function or class, got: undefined

Thank you, Mambo4! Very useful information for me!

I tried to use this in a file ms and run:


   (
  	      struct myStruct
  	      ( 	
  		   fn myFn =(print "my function in a struct")       
	 )
  	 myStructinstance=myStruct()
  )

and then from an mcr I’m calling

myStructinstance.myFn()

and it says:

– Frame:
– myStructinstance: undefined
>> MAXScript MacroScript Error Exception:
– Unknown property: “myFn” in undefined <<

howerver when I call the function myStructinstance.myFn() inside maxscript listener it’s working fine!

How to call the function from mcr file? I don’t want to run the whole script, I just need a portion of it.

First, the struct/struct instance has to be global so that you could access it. Second, if you only need the functions (that don’t rely on some variables inside the struct), you don’t have to make a struct instance:

(
	global myFnStruct, myVarStructInstance

	struct myFnStruct
	(
		fn myFn1 = print "function 1",
		fn myFn2 = print "function 2"
	)

	struct myVarStruct
	(
		emptyRollout = rollout emptyRollout "" (;);,
		fn showRollout = createDialog emptyRollout
	)
	myVarStructInstance = myVarStruct()
)

myFnStruct.myFn1() --> "function 1"
myVarStructInstance.showRollout()

Btw., in your code, you’re creating (well, not actually as you missed a comma and didn’t create the first instance) an instance of a struct itself when it gets created, creating a new instance and so on recursivelly which would shut down max.

Thank you, Vojta! I accidentally wrote this way here to simplify the idea.

What I did – I defined the struct global, and then I call from outside with ::

::struct.myfn()