| Message |
Lua starts to come into its own with its powerful support for what it calls "metatables".
By using these, we can greatly simplify the things you do a lot of in MUSHclient - accessing variables.
How many times have you written something like this in VBscript? ...
dim coins
coins = CInt (GetVariable ("coins"))
coins = coins + CInt (wildcards (2))
SetVariable "coins", coins
Here we have to muck around using GetVariable and SetVariable, as well as use CInt to convert strings into numbers.
Wouldn't it be nice to be able to write:
coins = coins + wildcards (2)
... and have that saved as a MUSHclient variable? Well, with Lua you can (almost).
To do this we need to create a dummy table, like this:
var = {} -- variables table
We will use that as our gateway to access MUSHclient variables. Now to make that work we need to make a "metatable" which implements two functions:
- __index - which is called when we attempt to get data from it
- __newindex - which is called when we attempt to add to it
These functions will call GetVariable and SetVariable to interface with MUSHclient variables.
Here is how it could look:
var = {} -- variables table
setmetatable (var,
{
-- called to access an entry
__index =
function (t, name)
return GetVariable (name)
end;
-- called to change or delete an entry
__newindex =
function (t, name, val)
local result
if val == nil then -- nil deletes it
result = DeleteVariable (name)
else
result = SetVariable (name, tostring (val))
end
-- warn if they are using bad variable names
if result == error_code.eInvalidObjectLabel then
error ("Bad variable name '" .. name .. "'")
end
end;
})
You could put that into your script file to be run when the world file opens. Now with that in place, we simply do this:
var.coins = var.coins + wildcards [2]
The "trick" here is the use of the "var" table - when we get data from that, or add to it, we go through the metamethod, which calls GetVariable and SetVariable, as shown above.
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|