Local Variables

From Scriptwiki
(Redirected from Category:Local Variables)
Jump to: navigation, search

Local variables are variables that exist only for the duration of the piece of script (for example an alias or event) in which they are created, and can only be accessed from within that piece of script - not from other anywhere else, not even from the aliases that the piece of script calls. Local variables are removed automatically when the piece of script is finished, so it is not required to /unset them. Local variables are very useful for storing short-lived data, such as loop counters and temporary results.

Local variables can be created with the /var command:

var %myvar = somevalue

Note that a local variable and a global variable (created with /set) with the same name may exist; in that case, the local variable will be used in the piece of script, and the global variable will not be changed.

You can set multiple variables at once:

var %x = foo, %y = bar

Although the '=' can be left out from the /var command in some cases, it is bad practice to do so: it can lead to weird errors in other lines.

You can use /var -s to make a variable show the result when a value is set.

Do not use /var to create local variables with a dynamic name (e.g. %x [ $+ [ %y ] ]), there is a bug in mIRC that prevents you from doing this.

Examples

First, let's create an alias that's used later on.

alias var_example { var -s %x = foo | set -s %y bar }

Now, let's play around.

; set values to variables with set so values exists until they're unset
set %x 10
set %y %x
; value from %x is copied to %y

; call of your own alias
var_example
; displays
; * Set %x to foo
; * Set %y to bar

; now, let's display %x and %y values
echo -a %x
; returns 10
echo -a %y
; returns bar

As we can see, %x still holds its original value because /var only creates a local variable, but %y was overwritten with /set.

See Also

  • /set is used when you want variables that exist between routines and aliases, call it global variables.
Contributed by Tovrleaf