Aliases as functions
From Scriptwiki
Revision as of 18:15, 2 September 2005 by BlackShroud (talk | contribs) (added links to other pages)
Most people think aliases are only used as custom commands, easier to use than typing a list of commands over and over again. When writing larger scripts however, aliases are often used as what are mostly called 'routines' or 'functions'.
This script will show an example of using aliases in such a way. It calculates how much percent of the persons in all the channels you're currently in are channel operators. All of this is to be used in remote.
;First, we will create an alias that gives us the amount of people ;in all your channels. alias totalpeople { ;declare the variables var %i = 1, %people ;use a while loop to go through every channel. while (%i <= $chan(0)) { ;add the amount of people in the channel the while loop is at to %people inc %people $nick($chan(%i),0) ;Make sure the while loops will go to the next channel. inc %i } ;Make the alias return the right value. return %people } ;From now on, $totalpeople will return the wanted amount. ;Now we will use a similar alias to count all the operators. The only difference ;is ,o added to the $nick identifier. As /help $nick states, this will make it ;only count channel operators. alias totalops { var %i = 1, %ops while (%i <= $chan(0)) { inc %ops $nick($chan(%i),0,o) inc %i } return %ops } ;This will make $totalops work too. ;As we wanted the result in percents, we should make a nice ;alias for that too. We are going to use 'arguments' again. alias percent { ;first we will make sure the two required arguments are used. If they aren't, the ;alias will return 0 instead of a value that is actually calculated. if (!$1 || !$2) { return 0 } else { ;now we use $calc with a small bit of maths to return the actual percentage. return $calc( $1 / $2 * 100 ) } } ;Usage of $percent will be $percent(A,B). This will show how many ;percent A is of B. ;Now let's create an alias as you're probably used to do. alias compareops { ;A simple echo will do the trick. I also use $round to make the output look a bit ;nicer with 2 decimals. echo $color(info) -a * $round($percent($totalops,$totalpeople),2) $+ $chr(37) of the people in all the channels you're currently in are channel operators. } ;You can now type /compareops to get the information you want.