Jump to content
meko

little known fact about getarg()

Recommended Posts

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

Another usage,

	function	test_f	{
		copyarray .@new_array,getarg(0),getarraysize(getarg(0));
		
		dispbottom .@new_array[0]; // --> 10
		dispbottom .@new_array[1]; // --> 20
		dispbottom .@new_array[2]; // --> 30
		dispbottom .@new_array[3]; // --> 40
		dispbottom .@new_array[4]; // --> 50
		
		return;
	}
	
	setarray .@array,10,20,30,40,50;
	
	test_f(.@array);

 

Share this post


Link to post
Share on other sites
9 minutes ago, Jeffery said:

Another usage,


	function	test_f	{
		copyarray .@new_array,getarg(0),getarraysize(getarg(0));
		
		dispbottom .@new_array[0]; // --> 10
		dispbottom .@new_array[1]; // --> 20
		dispbottom .@new_array[2]; // --> 30
		dispbottom .@new_array[3]; // --> 40
		dispbottom .@new_array[4]; // --> 50
		
		return;
	}
	
	setarray .@array,10,20,30,40,50;
	
	test_f(.@array);

 

this is a horrendous way to do it; instead of duplicating the array you should access directly with getelementofarray(getarg(0), index)

 

see this file for more examples: 

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.