What are loops and how do I use them

From Scriptwiki
Jump to: navigation, search

In many of the things you want to do with/in mIRC scripting you'll need a thing called loops. These can seem slightly complicated the first time you see them, but once you get the hang of if you will put them on your personal top10 of "things created by god".

mIRC can handle two different types of loops:

  • The 'while loop', which is used a lot in modern day scripting, and is the most important one.
  • The 'goto loop', which isn't half as common but useful from time to time.


The while loop looks something like the following,

var %i = 1
; first we create a variable to use as an important part of the actual loop.
while (%i <= 10) {
  ; here you see the statement (exactly like a regular if statement).
  ; basically what it does is:
  ; as long as %i is smaller than or equal to 10 do what are inside of my brackets.
  ; %i is the variable, and as it comes of the word this is the changable object in our loop,
  ; it has no constant value...
  echo -a %i
  ; inside the brackets we have this 'echo' that shows you the value of %i - the -a means it will echo in your active window.. easier to find.
  ; this will execute everytime it loops...
  inc %i
  ; at last we have the most important thing inside the loop, changing our variable that the
  ; loop is depending on. In this case, we increment it by one. Note that we don't do this inside the loop.

To describe it in a non scripting fashion, we could say:

as long as %i is lower than or equal to 10 we 'echo' the value of %i and increase it by 1. when increasing it by one each time the (%i <= 10) statement is true it will at some point not be true anymore, when we have increased %i's value to 11.

That was a very simple loop that explains how it works. Loops of that kind can eg. be used to show/return all the channels you are on:

var %i = 1
while (%i <= $chan(0)) {
  ; instead of the 10 we had as a value %i should be below in the first example, here it must
  ; be below $chan(0) which in mIRC scripting represents the total number of channels you are on.
  set %channels %channels $chan(%i)
  ; instead of just echoing each channel we are on which wouldn't make much sense we save the
  ; channels in a variable with 'set %channels %channels $chan(%i)'. $chan(%i) is the new channel
  ; we add to our variable each time it loops, as %i is the variable that keeps increasing till its
  ; no longer smaller than or equal to $chan(0). This will create a variable named %channels where
  ; all the channels you are in are saved when the loop is done.
  inc %i
  ; we always need to change the value of the variable the loop is depending on, if we forget to do
  ; this it will be an endless loop that might crash your mIRC/Computer.
echo -a %channels
; and at last we echo the contents of the variable %channels, which in this case is all the channels
; you are in, separated by spaces.

See Also

Contributed by Zyberdog