Passing function variables by reference

Hi,

I’m having some trouble passing variables by reference through a function and was hoping someone knew the correct syntax. I seem to be able to pass variables (and get back the changes I make to that variable in the called function) if I pass them as a list, but not if they are just a plain variable.

What’s the correct way to pass and change a function variable (e.g., the equivalent of calling:

foo( &var );

foo( int *var )
{
*var = 6;
}

in C ) ?

I have some sample code using “a reference to” and “contents of” but that only seems to work for passing the variable, not for getting different data back from the function.

Another way to go seems to be to pass the variable as a list and then set ‘item 1’ to the returning value. I figure there has got to be a better way. Any thoughts on this would be most appreciated.

Thanks,
Colin.

P.S. Yes, I know about using ‘return’ but I need to return more than one variable. Thanks.

Return multiple values from the function. ie,

set { newA, newB, newC } to myFunction( a,b,c )

on myFunction( a, b, c)
return { a, b, c }
end myFunction

As far as I know AppleScript only supports pass by value and not pass by reference (much like MatLab).

Here’s an example:

property a : 0
–set a to 1
set b to a reference to a
Incr(b)
a

on Incr(the_ref)
set (contents of the_ref) to the_ref + 1
return
end Incr

I made the variable ‘a’ a property so you can run it several times in the Script Editor otherwise if I used the ‘set’ statement, you would get the same value of 2.

gl,

Thanks for that feedback! It’s too bad about no straightforward passing by reference. I think I’ll just continue to use single-value-lists as a pseudo pass-by-reference for function calls that require it.

Kel:
I hadn’t thought of making all the variables that need to be passed properties, but that does solve the bug I was experiencing.

Interestingly, if the base value (‘a’) is not a global or property, you can’t set its value when passed. e.g.:


-- Uncomment the next line to make this script work
-- property a : 0

start()

on start()
	set a to 1
	set b to a reference to a
	Incr(b)
	a
end start

on Incr(the_ref)
	set contents of the_ref to the_ref + 1
	return
end Incr

Is this a bug I should report to Apple, or is there a logical reason why the thing which is being referred to must have global scope?

-Colin.

Hi,

I don’t know anything about javascript but I suspect that AppleScript is different. Don’t know if you know this but if you write this:

start()
--------- subroutines
on start()
end start

your call to start() is in an implicit run handler. This would be the same as:

on run
start()
end run
--------- subroutines
on start()
end start

but this time using an explicit run handler. Anyway, I don’t know what this means but maybe my thought is too deep for me to understand when conscious :-). Either that or it’s gibberish. Yeah, that’s probably it.

gl,