[Closed] Function calls question
When is it needed to add factors when calling a function?
say i have 3 variables.
local a
local b
local c
and i have a function storeABC
fn storeABC a b c =
(
a = 5
b = 5
c = 5
)
and i call it like this
storeABC a b c
now i’ve noticed that when i do it this way, and i try to bring say the variable “a” into another funcition…a is undefined
but if i don’t add parameters to my function when calling it works fine, and “a” is seen as 5
so the call is now simply storeABC() and the function line is fn storeABC =
which and when is the correct way to do either? If i’m doing something wrong here, i’m sorry for wasting your time.
Your second functions works because it is accessing variables that were defined previous to the function call, and you’re directly accessing those addresses that exist outside the scope of the function. The reason the first function didn’t work is because the variables a, b, and c only exist inside the function; once its done running, they are lost. This behavior is called “pass by value,” because only the values in the variables are sent to the function, not the variable itself.
If you want a “pass by reference” behavior, you can use MXS’s referencing and dereferencing capabilities, but note that they are rarely used. Check out the docs if you want to learn more – if you search for “reference” in the MXS help, the second topic to show up is a good article on this topic. Most scripters will just declare the variable in a scope that the function has access to, or simply not rely on such methods to assign values.
You’re not wasting time, I’m sure this is a topic lots of people have questions about at first, and its a difficult question to fit into a search criteria.
In max there’s a difference between undefined and unsupplied if I’m correct.
What happens in your case is that the variables outside the function are undefined, they have no value assigned to them. So when you pass that to the function, a is undefined (a as the parameter).
I don’t know how max ‘prioritises’ these things, but it looks like when you pass ‘a’ to something else in that function, it takes the parameter, not the local a in the function.
Something to make the structure of your script clearer would be to use different names for the local inside the function and the parameter.
If you want the parameter to have a default value when it’s not supplied or undefined you could use:
if (a == unsupplied) or (a == undefined) do (
a = 5
)
edit: @d3coy: yeah, practising this kind of stuff is indeed useful. Referencing in max can be done with the ampersand (&) sign.
Thanks both of you for the detailed explanation…definately clears things up for me.