little known fact about getarg()

meko

Core Developers
Messages
363
Points
0
IRC Nickname
meko
Github
Helianthella
Emulator
Hercules
Client Version
ManaPlus
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.

Code:
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
 
I can already see how people will use this as a bad habit.

Thanks for opening the box of pandora.

 
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.

 
Another usage,

Code:
	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);
 
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: 




 
Back
Top