meko

little known fact about getarg()

4 posts in this topic

When a function is invoked, the arguments are pushed to the stack, but if an argument is a scope variable its reference is also pushed. This means you can access variables of the parent scope from within a function.

 

function do_something {
    setarray(getarg(0), 69, 42, 1337);
    return;
}

debugmes(.@var[0]); // <= 0
debugmes(.@var[1]); // <= 0
debugmes(.@var[2]); // <= 0

do_something(.@var[0]);

debugmes(.@var[0]); // <= 69
debugmes(.@var[1]); // <= 42
debugmes(.@var[2]); // <= 1337

 

 

Share this post


Link to post
Share on other sites

I can already see how people will use this as a bad habit.

Thanks for opening the box of pandora.

Share this post


Link to post
Share on other sites

Actually it's pretty useful, it allows to pass custom variables instead of having the functions register hardcoded variables, and it avoids having to use getd. So if your function needs to return more than one value it can just ask for a variable as an argument, and fill it with the return data. The alternative would be to implode() the values, return, and then explode() after the function call, which is much dirtier.

Share this post


Link to post
Share on other sites

This is pretty neat and useful, I'll follow this for future scripting endeavors. Thanks!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now