Difference between revisions of "Manual:Advanced Lua"
(Size the image down) |
|||
Line 99: | Line 99: | ||
local stripped = rex.gsub("1.0.0", [[(\.0+)+$]], '') | local stripped = rex.gsub("1.0.0", [[(\.0+)+$]], '') | ||
print(stripped) | print(stripped) | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | The lrexlib manual can be hard to read, so the instructions in this section should provide most of what you need. | ||
+ | |||
+ | ''lrexlib'' does not come preinstalled, so you will have to install it. The easiest installation method uses ''luarocks''. There are a few flavors that you can specify, but in this section we will focus on the ''POSIX'' and ''PCRE'' flavors. | ||
+ | |||
+ | <syntaxhighlight lang="bash"> | ||
+ | luarocks install --local lrexlib-POSIX | ||
+ | luarocks install --local lrexlib-PCRE | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | After installation, you can use the library: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > local rex = require("rex_posix") | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | There are a few functions that you need to know: ''gsub'', ''count'', ''split'', ''find'', ''match''. | ||
+ | |||
+ | === Common behavior === | ||
+ | |||
+ | The ''count'' function counts the matches: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.count("ab", ".")) | ||
+ | 2 | ||
+ | </syntaxhighlight> | ||
+ | A single dot here has the same meaning it has in POSIX regexes. | ||
+ | |||
+ | You can also precompute the pattern, using the ''new'' function: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.count("ab", rex.new".")) | ||
+ | 2 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Regexes are greedy by default: | ||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.count("aaa", ".*")) | ||
+ | 1 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | The ''split'' function splits a string according to a regex pattern: | ||
+ | <syntaxhighlight lang="lua"> | ||
+ | > for a in rex.split("aba", "b") do | ||
+ | print(a) | ||
+ | end | ||
+ | a | ||
+ | a | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > for a in rex.split("aba", ",") do | ||
+ | print(a) | ||
+ | end | ||
+ | aba | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Be careful though, because the split does not consume all the characters with the same value, if they are adjacent: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > for a in rex.split("abba", "b") do | ||
+ | print(a) | ||
+ | end | ||
+ | a | ||
+ | |||
+ | a | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | The ''find'' function searches for the first match, and returns the offsets where the match starts and ends. | ||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.find("aaa", "b")) | ||
+ | nil | ||
+ | |||
+ | > print(rex.find("aba", "b")) | ||
+ | 2 2 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ''find'' also takes an additional parameter, which is the starting position: | ||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.find("abab", "b")) | ||
+ | 2 2 | ||
+ | > print(rex.find("abab", "b", 3)) | ||
+ | 4 4 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | A negative starting position will circle back from the end: | ||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.find("ababab", "b", -1)) | ||
+ | 6 6 | ||
+ | > print(rex.find("ababab", "b", -3)) | ||
+ | 4 4 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | The ''match'' function works similarly to the ''find'' function, but returns the matches instead of the indices: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.match("abcdef", "ab")) | ||
+ | ab | ||
+ | > print(rex.match("abcdef", ".*")) | ||
+ | abcdef | ||
+ | > print(rex.match("abcdef", "ab..")) | ||
+ | abcd | ||
+ | > print(rex.match("abcdef", ".*", 3)) | ||
+ | cdef | ||
+ | > print(rex.match("abcdef", ".*", -3)) | ||
+ | def | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | The ''gsub'' function replaces the pattern in the string, with the value in the third parameter: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.gsub("abcdef", "[abef]+", "")) | ||
+ | cd 2 2 | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | This snippet replaces all the "a", "b", "e" or "f" characters with the empty string, so only "c" and "d" remain. | ||
+ | |||
+ | The fourth parameter determines how many replacements are made: | ||
+ | |||
+ | <syntaxhighlight lang="lua"> | ||
+ | > print(rex.gsub("abcdef", "[abef]+", "", 1)) | ||
+ | cdef 1 1 | ||
+ | </syntaxhighlight> | ||
+ | Because the regex is greedy, the "ab" is a single match, so it gets replaced. | ||
+ | |||
+ | === PCRE specific functionality === | ||
+ | |||
+ | The case insensitive flag: | ||
+ | <syntaxhighlight lang="lua"> | ||
+ | > rex_pcre = require("rex_pcre") | ||
+ | > flags = rex_pcre.flags() | ||
+ | > print(rex_pcre.find("ABab", "a", 0, flags.CASELESS)) | ||
+ | 1 1 | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 06:54, 31 May 2023
Advanced Lua
Lua version
Mudlet uses Lua 5.1.
Lua tables
A good overview of tables is available on Lua's wiki in the TablesTutorial. Nick Gammon has also written a nice overview on how to deal with Lua tables.
How to use multimatches[n][m]
multimatches[n][m]
is the complement of matches[n]
when matching multi-line triggers. multimatches[n][m]
stores its matches by lines, inside each line are the relevant matches to it. The following example can be tested on the game batmud.bat.org:
In the case of a multiline trigger with these 2 Perl regex as conditions:
^You have (\w+) (\w+) (\w+) (\w+)
^You are (\w+).*(\w+).*
The command "score" generates the following output on batMUD:
You have an almost non-existent ability for avoiding hits. You are irreproachably kind. You have not completed any quests. You are refreshed, hungry, very young and brave. Conquer leads the human race. Hp:295/295 Sp:132/132 Ep:182/181 Exp:269 >
If you add this script to the trigger:
showMultimatches()
The script, i.e. the call to the function showMultimatches() generates this output:
-------------------------------------------------------
The table multimatches[n][m] contains:
-------------------------------------------------------
regex 1 captured: (multimatches[1][1-n])
key=1 value=You have not completed any quests
key=2 value=not
key=3 value=completed
key=4 value=any
key=5 value=quests
regex 2 captured: (multimatches[2][1-n])
key=1 value=You are refreshed, hungry, very young and brave
key=2 value=refreshed
key=3 value=young
key=4 value=and
key=5 value=brave
-------------------------------------------------------
The function showMultimatches() prints out the content of the table multimatches[n][m]. You can now see what the table multimatches[][] contains in this case. The first trigger condition (=regex 1) got as the first full match "You have not completed any quests". This is stored in multimatches[1][1] as the value of key=1 in the sub-table matches[1] which, in turn, is the value of key=1 of the table multimatches[n][m].
The structure of the table multimatches:
multimatches {
1 = {
matches[1] of regex 1
matches[2] of regex 1
matches[3] of regex 1
...
matches[m] of regex 1 },
2 = {
matches[1] of regex 2
matches[2] of regex 2
...
matches[m] of regex 2 },
... ...
n = {
matches[1] of regex n
matches[2] of regex n
...
matches[m] of regex n }
}
The sub-table matches[n] is the same table matches[n] you get when you have a standard non-multiline trigger. The value of the first key, i. e. matches[1], holds the first complete match of the regex. Subsequent keys hold the respective capture groups. For example: Let regex = "You have (\d+) gold and (\d+) silver" and the text from the game = "You have 5 gold and 7 silver coins in your bag." Then matches[1] contains "You have 5 gold and 7 silver", matches[2] = "5" and matches[3] = "7". In your script you could do:
myGold = myGold + tonumber( matches[2] )
mySilver = mySilver + tonumber( matches[3] )
However, if you’d like to use this script in the context of a multiline trigger, matches[] would not be defined as there are more than one regex. You need to use multimatches[n][m] in multiline triggers. Above script would look like this if above regex would be the first regex in the multiline trigger:
myGold = myGold + tonumber( multimatches[1][2] )
mySilver = mySilver + tonumber( multimatches[1][3] )
What makes multiline triggers really shine is the ability to react to game output that is spread over multiple lines and only fire the action (=run the script) if all conditions have been fulfilled in the specified amount of lines.
Regex in Lua
Lua has its own, fast and lightweight pattern matching built in - see 20.2 – Patterns. Should you need proper regex however, Mudlet has lrexlib available - which works as a drop-in replacement; replace string. with rex. - for example string.gsub to rex.gsub. See manual for documentation.
-- example: strip out trailing .0's from text using a regex
local stripped = rex.gsub("1.0.0", [[(\.0+)+$]], '')
print(stripped)
The lrexlib manual can be hard to read, so the instructions in this section should provide most of what you need.
lrexlib does not come preinstalled, so you will have to install it. The easiest installation method uses luarocks. There are a few flavors that you can specify, but in this section we will focus on the POSIX and PCRE flavors.
luarocks install --local lrexlib-POSIX
luarocks install --local lrexlib-PCRE
After installation, you can use the library:
> local rex = require("rex_posix")
There are a few functions that you need to know: gsub, count, split, find, match.
Common behavior
The count function counts the matches:
> print(rex.count("ab", "."))
2
A single dot here has the same meaning it has in POSIX regexes.
You can also precompute the pattern, using the new function:
> print(rex.count("ab", rex.new"."))
2
Regexes are greedy by default:
> print(rex.count("aaa", ".*"))
1
The split function splits a string according to a regex pattern:
> for a in rex.split("aba", "b") do
print(a)
end
a
a
> for a in rex.split("aba", ",") do
print(a)
end
aba
Be careful though, because the split does not consume all the characters with the same value, if they are adjacent:
> for a in rex.split("abba", "b") do
print(a)
end
a
a
The find function searches for the first match, and returns the offsets where the match starts and ends.
> print(rex.find("aaa", "b"))
nil
> print(rex.find("aba", "b"))
2 2
find also takes an additional parameter, which is the starting position:
> print(rex.find("abab", "b"))
2 2
> print(rex.find("abab", "b", 3))
4 4
A negative starting position will circle back from the end:
> print(rex.find("ababab", "b", -1))
6 6
> print(rex.find("ababab", "b", -3))
4 4
The match function works similarly to the find function, but returns the matches instead of the indices:
> print(rex.match("abcdef", "ab"))
ab
> print(rex.match("abcdef", ".*"))
abcdef
> print(rex.match("abcdef", "ab.."))
abcd
> print(rex.match("abcdef", ".*", 3))
cdef
> print(rex.match("abcdef", ".*", -3))
def
The gsub function replaces the pattern in the string, with the value in the third parameter:
> print(rex.gsub("abcdef", "[abef]+", ""))
cd 2 2
This snippet replaces all the "a", "b", "e" or "f" characters with the empty string, so only "c" and "d" remain.
The fourth parameter determines how many replacements are made:
> print(rex.gsub("abcdef", "[abef]+", "", 1))
cdef 1 1
Because the regex is greedy, the "ab" is a single match, so it gets replaced.
PCRE specific functionality
The case insensitive flag:
> rex_pcre = require("rex_pcre")
> flags = rex_pcre.flags()
> print(rex_pcre.find("ABab", "a", 0, flags.CASELESS))
1 1
Coroutines
Mudlet supports Lua's coroutines starting with 3.2.0, which opens up a whole lot of possibilities for the way you program your scripts. A pretty technical description and a tutorial is available, but for a quick explanation, think of coroutines allowing you to pause and resume running a function. If you're familiar with other clients, it is something like a #wait statement where a script will stop running, except unlike a #wait which auto-resumes the script later, you resume it when it yourself whenever you'd like.
Here's an example - add this code as a new script:
function ritual()
send("get wood")
-- think of coroutine.yield as yielding (giving away) control,
-- so the function will stop here and resume on making fire
-- when called the next time
coroutine.yield()
send("make fire")
coroutine.yield()
send("jump around")
coroutine.yield()
send("sacrifice goat")
end
Make a ^ritual$ alias - which seems big, but that's just because there's a lot of explanation inside it:
-- create a coroutine that'll be running our ritual function
-- or re-use the one we're already using if there is one
ritualcoroutine = ritualcoroutine or coroutine.create(ritual)
-- run the coroutine until a coroutine.yield() and see
-- if there's any more code to run
local moretocome = coroutine.resume(ritualcoroutine)
-- if there's no more code to run - remove the coroutine,
-- so next time you call the alias - a new one gets made
if not moretocome then
ritualcoroutine = nil
end
Now try doing the ritual command. You'll see that the send()'s are being sent one at a time, instead of all at once as they would have been without the yields. Cool, huh?
You can also install the demo as a package - paste this into Mudlet:
lua installPackage("http://wiki.mudlet.org/images/3/36/Ritual-coroutine-demo.zip")
Note that if you'll be using coroutines as part of a package you'll give to others, remember about the if mudlet.supportscoroutines then return end
bit. Older Mudlets that don't support coroutines might crash, which sucks. Newer ones that do support them are completely fine, however!
Coroutines have many uses: finite state machines, running intensive tasks (yielding every once in a while so Mudlet isn't frozen), and so on.
Introspective facilities
Lua brings a helpful debug.getinfo(function) function, which gets you some information about where a function comes from: whenever it's your own, or one defined by Mudlet (in C++ or Lua). You can also use it to get more information on the Alias## / Trigger## objects you see in the error console:
If you're working on coding Mudlet itself, use this function to tell where the actual definition of a function is.