User:Merlin11188/Draft: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Merlin11188
After creation of the quiz template, I embedded an example into this page.
>Merlin11188
Added a quiz.
Line 3: Line 3:
|<big>'''Do not edit!'''</big><br><small>The creator of this subpage does not want it to be edited without permission.</small>
|<big>'''Do not edit!'''</big><br><small>The creator of this subpage does not want it to be edited without permission.</small>
|}
|}
{{EmphasisBox|The metatables for [[Strings]] and all ROBLOX types are locked; however, in normal Lua (not RBX.lua) you can set the metatables of these objects using the debug library.[http://www.lua.org/manual/5.1/manual.html#5.9] |green|dark=yes}}
===Patterns===
==What is a Metatable?==
{{CatUp|Function Dump/String Manipulation}}
{{EmphasisBox|[[Image:RsClose_ds.png]] '''Note:''' This tutorial requires some knowledge of [[Function_Dump/String_Manipulation|string manipulation]].|red|}}
<br/>
Patterns are very useful tools for string manipulation. They allow you to do operations on all numbers in a string,
==Classes==
Character Class:


Metatables allow tables to become more powerful than before. They are attached to data and contain values called Metamethods. Metamethods are fired when a certain action is used with the datum that it is attached to.
A character class is used to represent a set of characters. The following are character classes and their representations:
You may think that if you have code like this:
*'''x'''  — Where x is any non-magic character (^$()%.[]*+-?), x represents itself
*'''.'''  — Represents all characters (#32kas321fslk#?@34)
*'''%a''' — Represents all letters (aBcDeFgHiJkLmNoPqRsTuVwXyZ)
*'''%c''' — Represents all control characters (all [http://wiki.roblox.com/index.php/Image:Ascii_Table.png ascii characters] below 32 and ascii character 127)
*'''%d''' — Represents all base-10 digits (1-10)
*'''%l''' — Represents all lower-case letters (abcdefghijklmnopqrstuvwxyz)
*'''%p''' — Represents all punctuation characters (#^;,.) etc.
*'''%s''' — Represents all space characters
*'''%u''' — Represents all upper-case letters (ABCDEFGHIJKLMNOPQRSTUVWXYZ)
*'''%w''' — Represents all alpha-numeric characters (aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789)
*'''%x''' — Represents all hexadecimal digits (0123456789ABCDEF)
*'''%z''' — Represents the [http://wiki.roblox.com/index.php/Image:Ascii_Table.png ascii character] with representation 0 (the null terminator)
*'''%x''' — Represents (where x is ''any non-alphanumeric character'') the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a '%' when used to represent itself in a pattern. So, a percent sign in a string is "%%"  <br/>
Here's an example:


<code lua>
{{Example|<pre>
local list = {1, 2}
String="Ha! You'll never find any of these (323414123114452) numbers inside me!"
print(list[3])
print(string.match(String, "%p")) -- Find a punctuation character
</code>


The code will search through the list for the third index in list, realize it's
Output:
not there, and return nil. That's totally wrong. What really happens is the code
! -- Exclamation point!
will search through the list for the third index, realize it's not there, and then
</pre>}}
try to see if there's a metatable attached to the table, returning nil if
there isn't one.


==setmetatable() and getmetatable()==
An upper-case version of any of these classes results in the complement of that class. For instance, %A will represent all
The two primary functions for giving and finding a table's metatable are setmetatable() and getmetatable().
non-letter characters. Cool thing? You can combine character classes! Here's another example:
<code lua>
{{Example|<pre>
local x = {}
Martian="141341432431413415072343E334141241312"
local metaTable = {}      -- metaTables are tables, too!
print(Martian:match("%D%d")) -- Find any non-digit character immediately followed by a digit.
setmetatable(x, metaTable) -- Give x a metatable called metaTable!
print(getmetatable(x)) --> table: [hexadecimal memory address]
</code>


==Metatable Demonstration==
Output:
E3
</pre>}}


{{Example|<code lua>
==Modifiers==
local list = {1, 2}
In Lua, modifiers are used for repetitions and optional parts. That's where they're useful; you can get more than one character at a time:
print("In table List, key \"z\" is "..tostring(list.z)) --> In table List, key "z" is nil
</code>


Now, look at what happens with metatables:
* + — 1 or more repetitions
* * — 0 or more repetitions
* - — (minus sign) also 0 or more repetitions
* ? — optional (0 or 1 occurrence)
<br/>
I'll start with the simplest one: the ?. This makes the character class optional, and if it's there, captures 1 of it. That sounds complex, but is actually really simple, so here's an example:
{{Example|<pre>
stringToMatch="Once upon a time, in a land far, far away..."
print(stringToMatch:match("%a?")) -- Find a letter, but it doesn't have to be there.
print(stringToMatch:match("%d?")) -- Find a number, but it doesn't have to be there.


<code lua>
Output:
local list = {1, 2}      -- A normal table
O -- O, in Once.
local metatable = {      -- A metatable
--Nothing because the digit didn't need to be there, so nothing was returned.
__index = function(t, key)
</pre>}}
rawset(t, key, 0) -- Set t[key] to 0
<br/>
return t[key]    -- return t[key] (which is now 0)
The + symbol used after a character class requires at least one instance of that class, and will get the longest string of that class. Here's an example:
end
{{Example|<pre>
}
stringToMatch="Once upon a time, in a land far, far away..."
setmetatable(list, metatable) -- Now list has the metatable metatable
print(stringToMatch:match("%a+")) -- Finds the first letter, then matches letters until a non-letter character
print("In table List, key \"z\" is "..tostring(list.z)) --> In table List, key "z" is 0
print(stringToMatch:match("%d+")) -- Finds the first number, then matches numbers until a non-number character
</code>}}


What happened there? <tt>list</tt> is a normal table, with nothing unusual about it. <tt>metatable</tt> is also a table, but it has something special: the <tt>__index</tt> metamethod. The <tt>__index</tt> metamethod is fired when <tt>t[key]</tt> is nil, or in this case, <tt>list.z</tt> is nil. Now, nothing would happen because the two tables (<tt>list</tt> and <tt>metatable</tt>) aren't linked. That's what the third line does: sets <tt>list</tt>'s metatable to <tt>metatable</tt>, which means that when <tt>list</tt> is indexed (<tt>__index</tt>) at an index that's nil (<tt>list.z</tt>), the function associated with <tt>__index</tt> in Metatable is run. The function at <tt>__index</tt> in <tt>metatable</tt> uses <tt>rawset</tt> to make a new value in the Table (or <tt>list</tt>). Then, that value is returned. So, <tt>list.z</tt> is set to 0, and then <tt>list.z</tt> is returned (which is 0).
Output:
Once
nil -- Nil because the pattern required the digit to be there, but it wasn't, which returns nil.
</pre>}}
<br/>
The * symbol used after a character class is like a combination of the + and ? modifiers. It matches the longest sequence of the character class, but it doesn't have to be there. Here's an example of it matching a floating-point (decimal) number, without requiring the decimal:
{{Example|<pre>
numPattern="%d+%.?%d*"
--[[ Requires there to be an integer, and if there's a decimal point, get it (remember: a period is magic character, so you have to escape it with the % sign), and if there are numbers after the decimal point, grab them. ]]


==Metamethods==
local num1="21608347 is an integer, a whole number, and a natural number!"
local num2="2034782.014873 is a decimal number!"
print(num1:match(numPattern))
print(num2:match(numPattern))


Metamethods are the functions that are stored inside a metatable. They can go from
Output:
calling a table, to adding a table, to even dividing tables as well. Here's a list
21608347 -- Grabbed the whole number, but there wasn't a decimal point nor were there numbers after the decimal point
of metamethods that can be used:
2034782.014873 -- Grabbed the floating-point number, because it had a decimal and numbers after it
</pre>}}
<br/>
The - symbol used after a character class is like the * symbol; actually, there's only one difference: It matches the shortest sequence of the character class. Here's an example showing the difference:
{{Example|<pre>
String="((3+4)+3+4)+2"
print(String:match("%(.*%)")) -- Find a (, then match all (the . represens all characters) characters until the LAST ).
print(String:match("%(.-%)")) -- Find a (, then match all characters until the FIRST ).


*__index(Table, Index) — Fires when Table[Index] is nil.
Output:
*__newindex(Table, Index, Value) — Fires when Table[Index] = Value when Table[Index] is nil.
((3+4)+3+4) -- Grabbed everything from the first opening parenthesis to the last closing parenthesis
*__call(Table, arg) — Allows the table to be used as a function, arg is the arguments passed, Table(arg).
((3+4)     -- Grabbed everything from the first opening parenthesis to the first closing parenthesis
*__concat(Table, Object) — The .. concatenation operator.
</pre>}}
*__unm(Table) — The unary – operator.
*__add(Table, Object) — The + addition operator.
*__sub(Table, Object) — The – subtraction operator.
*__mul(Table, Object) — The * mulitplication operator.
*__div(Table, Object) — The / division operator.
*__mod(Table, Object) — The % modulus operator.
*__pow(Table, Object) — The ^ exponentiation operator.
*__tostring(Table) — Fired when tostring is called on the table.
*__metatable — if present, locks the metatable so getmetatable will return this instead of the metatable and setmetatable will error. Non-function value.
*__eq(Table, Table2) — The == equal to operator˚
*__lt(Table, Table2) — The < less than operator˚
*__le(Table, Table2) — The <= operator˚
*__mode — Used in [[Weak Tables]], declaring whether the keys and/or values of a table are weak.
*__gc(Object) — Fired when the Object is garbage-collected.
*__len(Object) — Fired when the # operator is used on the Object. '''NOTE:''' Only userdatas actually respect the __len() metamethod, this is a bug in Lua 5.1


˚ Requires two tables; does not work with a table and a number, string, etc. The tables must have the '''same''' metatable.
==Sets==
* '''[set]''' represents the class which is the union of all characters in the set. You define a set with brackets, like [%a%d]. A range of characters may be specified by separating the end characters of the range with a '-'. All classes described above may also be used as components in set. All other characters in a set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the '-' character.


==Using Metatables==
The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.
* '''[^set]''' represents the complement of set, where set is interpreted as above.


There are many ways to use metatables, for example the __unm metamethod (to make a table negative):
{{Example|<pre>
{{Example|<code lua>
Vowel="[AEIOUaeiou]" -- Match a vowel, upper-case or lower-case
local table1 = {10,11,12}
Nonvowel="[^AEIOUaeiou]" -- Match any non-vowel by using the complement of the vowel set
local metatable = {
OctalDigit="[0-7]" -- Match an octal digit. Octal digits: 0,1,2,3,4,5,6,7
__unm = function(t) -- __unm is for the unary operator -
stringToMatch="I have several vowels and consonants, and I'm followed by an octal number: 0231356701"
local negatedTable = {} -- the table to return
print(stringToMatch:match(Vowel))
for key, value in pairs(t) do
print(stringToMatch:match(Nonvowel))
negatedTable[key] = -value
print(stringToMatch:match(OctalDigit))
end
return negatedTable -- return the negative Table!
end
}


setmetatable(table1, metatable)
Output:
print(table.concat(-table1, "; ")) --> -10; -11; -12
I-- First vowel
</code>}}
-- This is a space; it was the first non-vowel character (after the I).
0-- First octal digit, late in the string.
</pre>}}  


Here's an interesting way to declare things using __index:
==Pattern Items==
{{Example|<code lua>
local t = {}
local metatable = {
__index = {x = 1}
}
setmetatable(t, metatable)
print(t.x) --> 1
</code>}}


__index was fired when x was accessed from the table. __index then defined x as 1 instead of nil; therefore, 1 was returned.
Alright, now it's time to explain what a pattern item is. A pattern item may be:


Now you can easily do that with a simple function, but there's a lot more where
* a single character class, which matches any single character in the class;
that came from. Take this for example:
* a single character class followed by '*', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
<code lua>
* a single character class followed by '+', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
local table = {10, 20, 30}
* a single character class followed by '-', which also matches 0 or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;
print(table(5))
* a single character class followed by '?', which matches 0 or 1 occurrence of a character in the class;
</code>
* %n, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see Captures below);
* %bxy, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item %b() matches expressions with balanced parentheses.


Now, obviously you can't call a table. That's just crazy, but (surprise, surprise!)
{{Example|<pre>
with metatables you can.
local Code="((I'm hiding inside parentheses!) I'll never) be found!"
print(Code:match("%b()"))


{{Example|<code lua>
Output:
local Table = {10, 20, 30}
((I'm hiding inside parentheses!) I'll never) -- First opening parenthesis out of 2, second closing parenthesis out of 3
</pre>}}
local metatable = {
The pattern found two opening parentheses, so it went to find two closing ones, trapping everything in between the first opening parenthesis and the second closing parenthesis.
__call = function(Table, param)
local sum = {}
for i, value in ipairs(Table) do
sum[i] = value + param -- Add the argument (5) to the value, then place it in the new table (t).
end
return unpack(sum) -- Return the individual table values
end
}
 
setmetatable(Table, metatable)
print(Table(5)) --> 15 25  35
</code>}}
 
You can do a lot more as well, such as adding tables!
{{Example|<code lua>
local table1 = {10, 11, 12}
local table2 = {13, 14, 15}
 
for k, v in pairs(table1 + table2) do
print(k, v)
end
</code>


This will error saying that you're attempting to perform arithmetic on a table.  Let's try this with a metatable.
Pattern:
<code lua>
local table1 = {10, 11, 12}
local table2 = {13, 14, 15}


local metatable = {
A pattern is a sequence of pattern items. A '^' at the beginning of a pattern anchors the match at the beginning of the string. A '$' at the end of a pattern anchors the match at the end of the string. At other positions, '^' and '$' have no special meaning and represent themselves. Also, a pattern cannot contain embedded zeroes. Use %z instead. Here's an example of a pattern:
__add = function(table1, table2)
local sum = {}
for key, value in pairs(table1) do
if table2[key] ~= nil then -- Does this key exist in that table?
sum[key] = value + table2[key]
else                      -- If not, add 0.
sum[key] = value
end
end
    -- Add all the keys in table2 that aren't in table 1
for key, value in pairs(table2) do
if sum[key] == nil then
sum[key] = value
end
end
return sum
end
}
setmetatable(table1, metatable)
setmetatable(table2, metatable)


for k, v in pairs(table1 + table2) do
{{Example|<pre>
print(k, v)
local Pattern="[%w%s%p]*" -- Get the longest sequence containing alpha-numeric characters, punctuation marks, and spaces.
end
local Pattern2="^%a+" -- The string has to start with a sequence of letters.
x="Hello, my name is Merlin!"
print(x:match(Pattern))
print(x:match(Pattern2))


--[[
Output:
Output:
Hello, my name is Merlin! -- The entire string contained only alpha-numeric characters, punctuation marks, and spaces!
Hello -- Matched only the letters at the start of the string.
</pre>}}


1 23
==Captures==
2 25
3 27
]]
</code>}}


If the two tables have two different __add functions, then Lua will go to table1
A pattern may contain sub-patterns enclosed in parentheses; they describe captures. When a match of a capture succeeds, the substring that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the first capture (and therefore has number 1); the character matching "." is captured with number 2, and the part matching "%s*" has number 3. Whaaaaat??? Here:
first and if it doesn't have an __add function, then it'll go to the second one. That
{{Example|<pre>
means that you really only have to set the metatable of Table1 or Table2, but it's
local number="55"
nicer and more readable to set the metatable of both.
print(number:find("%d%d")) -- Find returns the location of the match, not the match itself
print(number:find("(%d%d)"))


Here is one last example breaking away from using separate variables when it isn't necessary.
Ouput:
{{Example|<code lua>
1 2          -- The first digit is at number:sub(1,1) and the second digit is at number:sub(2,2)
local t = setmetatable({
1 2 55 -- The 55 is captured and returned.
10, 20, 30
</pre>}}
}, {
The second string had the parentheses represent a capture of one digit immediately followed by another. So, what a capture does is return whatever the function returns, which, for string.find, are the locations, as well as the ''matched substring''. What's inside the parentheses is the substring that is being matched. So, the %d%d was the substring that was to be matched, and it was returned along with the 1 and the 2, the values the function returns, followed by the matched substring (55).
__call = function(a, b)
return table.concat(a, b .. ' ') .. b
end
})
print('Tables contains '..t(1)) --> Tables contains 101 201 301
</code>}}


==rawset(), rawget(), rawequal()==
As a special case, the empty capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "flaaap", there will be two captures: 3 and 5.
If you continue to play with metatables, you might encounter problems. Here's a primary example:


Let's say that we want to make a table error() whenever you try to access a nil value in it.
==Quiz==
<code lua>
local planets = {Earth = "COOL!"}
local mt = {
__index = function(self, i)
return self[i] or error(i .. " is not a real Planet!") -- If self[i] is nil, then error!
end
}


setmetatable(planets, mt);
{{Quiz|title=Quiz on Patterns|
print(planets.Earth);    --> COOL!
#What would be returned if you matched this pattern (assuming it is not nil): <tt>%a%s%d%p</tt>?
print(planets.Pluto);    --> error: C stack overflow
#What would the following code return? <code lua>
local Test = "Some games are very fun and adventurous!!@#!12468134972@#@!$!!"
print(Test:match("%p-%d+%p"))
</code>
</code>
 
#How does the '''-''' modifier differ from the '''*''' modifier?
So what does <tt>C stack overflow</tt> mean?
#What is the simplest way to match "merlin11188" (including the quotes)?
It means you've called the same function too many times inside of itself (or recursed too deeply). You called a function too many times too quickly! The normal limit is actually right around 20,000!
|
 
#You would get a letter, followed by a space, followed by a single-digit number, followed by a punctuation mark.
So what caused the <tt>__index()</tt> method to call itself ?
#!!@#!12468134972@
The answer: <tt>self[i]</tt>
#The '''-''' modifier differs from the '''*''' modifier because the minus matches the shortest repetition of a character class, and the asterisk matches the longest.
 
#Trick question. There are multiple ways to do this, but the simplest is undoubtedly: <code lua>
So what can we do? How can we get a member of a table without calling it's <tt>__index()</tt> method?
local String = 'I have an account on ROBLOX. Signed, "merlin11188" (Definitely my signature)'
With [[Function_Dump/Core_Functions#rawget_.28table.2C_index.29|rawget()]], of course!
String:match('"merlin11188"')
 
 
{{EmphasisBox|[[Function_Dump/Core_Functions#rawget_.28table.2C_index.29|rawget()]], [[Function_Dump/Core_Functions#rawset_.28table.2C_index.2C_value.29|rawset()]], and [[Function_Dump/Core_Functions#rawequal_.28v1.2C_v2.29|rawequal()]] are very important when making custom metatables because they do not invoke a table's metamethods, so things like __index and __newindex aren't activated!}}
 
 
Let's make a small change to the code and try again!
<code lua>
local planets = {Earth = "COOL!"}
local mt = {
__index = function(self, i)
return rawget(self, i) or error(i .. " is not a real Planet!")
end
}
setmetatable(planets, mt)
print(planets.Earth)    --> COOL!
print(planets.Pluto)    --> error: Pluto is not a real Planet!
</code>
 
 
 
==Use Cases==
 
Now, I am well aware that you can do all of these as a simple function yourself,
but there's a lot more than what you think it can do. Let's try a simple program
that will memorize a number when a possibly laggy math problem is put into it.
 
For this one we will be using the __index metamethod just to make it simple:
 
{{Example|<code lua>
local Table = {}
 
local function mathProblem(num)
for i = 1, 20 do
num = math.floor(num * 10 + 65)
end
for i = 1, 10 do
num = num + i - 1
end
return num
end
 
local Metatable = {
__index = function (object, key)
local num = mathProblem(key)
object[key] = num
return num
end
}
 
local setmetatable(Table, Metatable)
 
print(Table[1]) -- Will be slow because it's the first time using this number.
print(Table[2]) -- will be slow because it's the first time using this number.
print(Table[1]) -- will be fast because it's just grabbing the number from the table.
</code>}}
</code>}}


==Quiz==
{{Template:Quiz|
#Without looking at the list above, which metamethod allows you to add two tables?
#Without looking at the list above, which metamethod allows you to negate a table?
#If run, what will the following code result in?<code lua>
local quizTable = {"Hello", "Hi", "Bonjour"}
setmetatable(quizTable, {__index = function(parent, key)
rawset(parent, key, key * 2 .. tostring(rawget(parent, key/2)))
return key * 2 .. tostring(rawget(parent, key/2))
end})
print(quizTable[6])
</code>
|
#__add. Pretty easy.
#__unm.
#12Bonjour
}}


==See Also==
==See Also==
 
http://www.lua.org/pil/20.2.html<br/>
http://www.lua.org/manual/5.1/manual.html#2.8
http://www.lua.org/pil/20.3.html
 
http://www.lua.org/pil
 
[[Category:Scripting_Tutorials]]

Revision as of 19:55, 16 January 2012

Do not edit!
The creator of this subpage does not want it to be edited without permission.

Patterns

Note: This tutorial requires some knowledge of string manipulation.


Patterns are very useful tools for string manipulation. They allow you to do operations on all numbers in a string,

Classes

Character Class:

A character class is used to represent a set of characters. The following are character classes and their representations:

  • x — Where x is any non-magic character (^$()%.[]*+-?), x represents itself
  • . — Represents all characters (#32kas321fslk#?@34)
  • %a — Represents all letters (aBcDeFgHiJkLmNoPqRsTuVwXyZ)
  • %c — Represents all control characters (all ascii characters below 32 and ascii character 127)
  • %d — Represents all base-10 digits (1-10)
  • %l — Represents all lower-case letters (abcdefghijklmnopqrstuvwxyz)
  • %p — Represents all punctuation characters (#^;,.) etc.
  • %s — Represents all space characters
  • %u — Represents all upper-case letters (ABCDEFGHIJKLMNOPQRSTUVWXYZ)
  • %w — Represents all alpha-numeric characters (aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789)
  • %x — Represents all hexadecimal digits (0123456789ABCDEF)
  • %z — Represents the ascii character with representation 0 (the null terminator)
  • %x — Represents (where x is any non-alphanumeric character) the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a '%' when used to represent itself in a pattern. So, a percent sign in a string is "%%"

Here's an example:

Example
String="Ha! You'll never find any of these (323414123114452) numbers inside me!"
print(string.match(String, "%p")) -- Find a punctuation character

Output:
! -- Exclamation point!


An upper-case version of any of these classes results in the complement of that class. For instance, %A will represent all non-letter characters. Cool thing? You can combine character classes! Here's another example:

Example
Martian="141341432431413415072343E334141241312"
print(Martian:match("%D%d")) -- Find any non-digit character immediately followed by a digit.

Output:
E3


Modifiers

In Lua, modifiers are used for repetitions and optional parts. That's where they're useful; you can get more than one character at a time:

  • + — 1 or more repetitions
  • * — 0 or more repetitions
  • - — (minus sign) also 0 or more repetitions
  • ? — optional (0 or 1 occurrence)


I'll start with the simplest one: the ?. This makes the character class optional, and if it's there, captures 1 of it. That sounds complex, but is actually really simple, so here's an example:

Example
stringToMatch="Once upon a time, in a land far, far away..."
print(stringToMatch:match("%a?")) -- Find a letter, but it doesn't have to be there.
print(stringToMatch:match("%d?")) -- Find a number, but it doesn't have to be there.

Output:
O -- O, in Once.
--Nothing because the digit didn't need to be there, so nothing was returned.


The + symbol used after a character class requires at least one instance of that class, and will get the longest string of that class. Here's an example:

Example
stringToMatch="Once upon a time, in a land far, far away..."
print(stringToMatch:match("%a+")) -- Finds the first letter, then matches letters until a non-letter character
print(stringToMatch:match("%d+")) -- Finds the first number, then matches numbers until a non-number character

Output:
Once
nil -- Nil because the pattern required the digit to be there, but it wasn't, which returns nil.


The * symbol used after a character class is like a combination of the + and ? modifiers. It matches the longest sequence of the character class, but it doesn't have to be there. Here's an example of it matching a floating-point (decimal) number, without requiring the decimal:

Example
numPattern="%d+%.?%d*"
--[[ Requires there to be an integer, and if there's a decimal point, get it (remember: a period is magic character, so you have to escape it with the % sign), and if there are numbers after the decimal point, grab them. ]]

local num1="21608347 is an integer, a whole number, and a natural number!"
local num2="2034782.014873 is a decimal number!"
print(num1:match(numPattern))
print(num2:match(numPattern))

Output:
21608347 -- Grabbed the whole number, but there wasn't a decimal point nor were there numbers after the decimal point
2034782.014873 -- Grabbed the floating-point number, because it had a decimal and numbers after it


The - symbol used after a character class is like the * symbol; actually, there's only one difference: It matches the shortest sequence of the character class. Here's an example showing the difference:

Example
String="((3+4)+3+4)+2"
print(String:match("%(.*%)")) -- Find a (, then match all (the . represens all characters) characters until the LAST ).
print(String:match("%(.-%)")) -- Find a (, then match all characters until the FIRST ).

Output:
((3+4)+3+4) -- Grabbed everything from the first opening parenthesis to the last closing parenthesis
((3+4)      -- Grabbed everything from the first opening parenthesis to the first closing parenthesis


Sets

  • [set] represents the class which is the union of all characters in the set. You define a set with brackets, like [%a%d]. A range of characters may be specified by separating the end characters of the range with a '-'. All classes described above may also be used as components in set. All other characters in a set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the '-' character.

The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.

  • [^set] represents the complement of set, where set is interpreted as above.
Example
Vowel="[AEIOUaeiou]" -- Match a vowel, upper-case or lower-case
Nonvowel="[^AEIOUaeiou]" -- Match any non-vowel by using the complement of the vowel set
OctalDigit="[0-7]" -- Match an octal digit. Octal digits: 0,1,2,3,4,5,6,7
stringToMatch="I have several vowels and consonants, and I'm followed by an octal number: 0231356701"
print(stringToMatch:match(Vowel))
print(stringToMatch:match(Nonvowel))
print(stringToMatch:match(OctalDigit))

Output:
I-- First vowel
 -- This is a space; it was the first non-vowel character (after the I).
0-- First octal digit, late in the string.


Pattern Items

Alright, now it's time to explain what a pattern item is. A pattern item may be:

  • a single character class, which matches any single character in the class;
  • a single character class followed by '*', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by '+', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by '-', which also matches 0 or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;
  • a single character class followed by '?', which matches 0 or 1 occurrence of a character in the class;
  • %n, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see Captures below);
  • %bxy, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item %b() matches expressions with balanced parentheses.
Example
local Code="((I'm hiding inside parentheses!) I'll never) be found!"
print(Code:match("%b()"))

Output:
((I'm hiding inside parentheses!) I'll never) -- First opening parenthesis out of 2, second closing parenthesis out of 3

The pattern found two opening parentheses, so it went to find two closing ones, trapping everything in between the first opening parenthesis and the second closing parenthesis.

Pattern:

A pattern is a sequence of pattern items. A '^' at the beginning of a pattern anchors the match at the beginning of the string. A '$' at the end of a pattern anchors the match at the end of the string. At other positions, '^' and '$' have no special meaning and represent themselves. Also, a pattern cannot contain embedded zeroes. Use %z instead. Here's an example of a pattern:

Example
local Pattern="[%w%s%p]*" -- Get the longest sequence containing alpha-numeric characters, punctuation marks, and spaces.
local Pattern2="^%a+" -- The string has to start with a sequence of letters.
x="Hello, my name is Merlin!"
print(x:match(Pattern))
print(x:match(Pattern2))

Output:
Hello, my name is Merlin! -- The entire string contained only alpha-numeric characters, punctuation marks, and spaces!
Hello -- Matched only the letters at the start of the string.


Captures

A pattern may contain sub-patterns enclosed in parentheses; they describe captures. When a match of a capture succeeds, the substring that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the first capture (and therefore has number 1); the character matching "." is captured with number 2, and the part matching "%s*" has number 3. Whaaaaat??? Here:

Example
local number="55"
print(number:find("%d%d")) -- Find returns the location of the match, not the match itself
print(number:find("(%d%d)"))

Ouput:
1	2          -- The first digit is at number:sub(1,1) and the second digit is at number:sub(2,2)
1	2	55 -- The 55 is captured and returned.

The second string had the parentheses represent a capture of one digit immediately followed by another. So, what a capture does is return whatever the function returns, which, for string.find, are the locations, as well as the matched substring. What's inside the parentheses is the substring that is being matched. So, the %d%d was the substring that was to be matched, and it was returned along with the 1 and the 2, the values the function returns, followed by the matched substring (55).

As a special case, the empty capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "flaaap", there will be two captures: 3 and 5.

Quiz

Quiz on Patterns


{{{1}}}

Note: This is a quiz. The answers are not explained. If you don't understand, review this page, then ask in the forums {{{2}}}



See Also

http://www.lua.org/pil/20.2.html
http://www.lua.org/pil/20.3.html