Script firing, will not add to Variable

Posted by Jakaiya on Sat 29 Mar 2008 09:12 AM — 4 posts, 21,860 views.

#0
I am trying to set a trigger that adds to a variable but I cannot get it to add

Trigger line
^\[Level Gain\] You gain a level\.$

Script
NewLevel = @NewLevel + 1
Note ("[SYSTEM]: New Level! You are now Level @NewLevel")


Variable
NewLevel

It fires but does not add 1 to the NewLevel variable.
It keeps displaying the old level.

Any Idea how I can fix this?
Russia #1
You are confusing two different types of variables: script and Mushclient. You are assigning the value of a Mushclient variable plus 1 to a script variable and then displaying the Mushclient variable, which never changes. Here's what you actually want to do:


SetVariable("NewLevel", @NewLevel + 1)
Australia Forum Administrator #2
Ked is correct, but his reply won't totally solve your problem. To understand why, you need to realize that MUSHclient substitutes variables in the "Send" box at the start, before sending to the MUD, or the script engine.

Say, for example, you are level 20. Thus your script now reads (before it executes):


NewLevel = 20 + 1
Note ("[SYSTEM]: New Level! You are now Level 20")


You can see this will always display the current level.

Also, as Ked says you have altered a Lua variable, not a MUSHclient variable. The answer is to use scripted access to variables, in both places:


SetVariable ("NewLevel", GetVariable("NewLevel") + 1)
Note ("[SYSTEM]: New Level! You are now Level " .. GetVariable("NewLevel"))


Now the second line retrieves the incremented level number.

You can make it neater by using the "var" module which comes with MUSHclient, like this:


require "var"

var.NewLevel = var.NewLevel + 1
Note ("[SYSTEM]: New Level! You are now Level " .. var.NewLevel)


The "var.<something>" syntax gives you access to MUSHclient variables, by using a special Lua table with a metatable on it. This is described here:

http://www.gammon.com.au/forum/?id=4904


On a new world the above script will fail initially because var.NewLevel will be nil (that is, the variable won't exist).

You can fix this by doing this:


require "var"

var.NewLevel = (var.NewLevel or 0) + 1
Note ("[SYSTEM]: New Level! You are now Level " .. var.NewLevel)


The "or 0" part says that if the variable doesn't exist, default it to zero. (Maybe make that 1 if that is your starting level).
Amended on Sat 29 Mar 2008 08:23 PM by Nick Gammon
#3
Thanks that worked perfectly. I will learn Lua and Mushclient if it kills me.