[MAXScript] An Odd Error - Code Works But Not When Used In A Function

Hello,

I have what appears to be a very simple “Attempt to access deleted scene object” error:


(
	local myArray = #(), myArray2 = #() -- myArray is used in the function, myArray2 is used directly in the myTest2 spinner event handler expression
	
	function myTestFn myFnArray myVal = 
	(       -- if the array has 1 or more elements in it, delete them and then reset the array to #()
		if myFnArray.count > 0 do
		(
			for a in myFnArray do delete a
			myFnArray = #()
		)
		-- during each loop, create a default box and append it to the array
		for a in 1 to myVal do
		(
			myBox = Box()
			append myFnArray myBox
		)
	)
	
	rollout testR "Test"
	(
		spinner myTest "Number:" type:#integer
		
		on myTest changed val do
			myTestFn myArray val -- call the function using myTest as the array and the spinner value as myVal
		
		spinner myTest2 "Number:" type:#integer
		-- do the same as above but without using a function
		on myTest2 changed val do
		(
			if myArray2.count > 0 then
			(
				for a in myArray2 do delete a
				myArray2 = #()
			)
			
			for a in 1 to val do
			(
				myBox = Box()
				append myArray2 myBox
			)
		)
	)
	createDialog testR
)

What happens is that when I change the first spinner, myTest, more than twice I get a runtime error saying that I’m trying to access a delete scene node, but as you can see I’ve used the same code in the second spinner, myTest2, and everything works fine when it is changed.

I’m working on script which has quite a lot of repetitive code, so I really want to use functions.

Hopefully someone can help!

Thanks,
-Harry

The error occurs because when calling the function, myArray is being sent to the function “by-value” and not “by-reference”, thus myArray does not get updated after the function call and is still storing the deleted object in the array.

Change the function:

	function myTestFn &myFnArray myVal = 
	(       -- if the array has 1 or more elements in it, delete them and then reset the array to #()
		if myFnArray.count > 0 do
		(
			for a in myFnArray do delete a
			myFnArray = #()
		)
		-- during each loop, create a default box and append it to the array
		for a in 1 to myVal do
		(
			myBox = Box()
			append myFnArray myBox
		)
	)

call the function using:

myTestFn &myArray val -- call the function using myTest as the array and the spinner value as myVal

Thank you, that works now and explains why the spinner was giving me the error on the third value change and thank you for pointing out the exact problem, there’s a good page in the MAXScript documentation which explains the topic at length.