Difference between revisions of "String.gmatch"
m |
m (Text replacement - "<source" to "<syntaxhighlight") |
||
Line 5: | Line 5: | ||
=== Description === | === Description === | ||
Returns an iterator function that, each time it is called, returns the next captures from pattern ''pat'' over string ''s''. If pattern specifies no captures, then the whole match is produced in each call. | Returns an iterator function that, each time it is called, returns the next captures from pattern ''pat'' over string ''s''. If pattern specifies no captures, then the whole match is produced in each call. | ||
− | < | + | <syntaxhighlight lang="lua"> |
(function) = string.gmatch(s,pat) | (function) = string.gmatch(s,pat) | ||
</source> | </source> | ||
Line 18: | Line 18: | ||
=== Examples === | === Examples === | ||
'''The following loop will iterate over all the words from string s, printing one per line''' | '''The following loop will iterate over all the words from string s, printing one per line''' | ||
− | < | + | <syntaxhighlight lang="lua"> |
s = "hello world from Lua" | s = "hello world from Lua" | ||
for w in string.gmatch(s, "%a+") do | for w in string.gmatch(s, "%a+") do | ||
Line 27: | Line 27: | ||
'''The next example collects all pairs key=value from the given string into a table''' | '''The next example collects all pairs key=value from the given string into a table''' | ||
− | < | + | <syntaxhighlight lang="lua"> |
t = {} | t = {} | ||
s = "from=world, to=Lua" | s = "from=world, to=Lua" |
Revision as of 14:31, 13 July 2023
Available since: Gideros 2011.6
Class: string
Description
Returns an iterator function that, each time it is called, returns the next captures from pattern pat over string s. If pattern specifies no captures, then the whole match is produced in each call. <syntaxhighlight lang="lua"> (function) = string.gmatch(s,pat) </source>
Parameters
s: (string) string where to look for patterns
pat: (string) pattern to look for
Return values
Returns (function) iterator function
Examples
The following loop will iterate over all the words from string s, printing one per line <syntaxhighlight lang="lua"> s = "hello world from Lua" for w in string.gmatch(s, "%a+") do
print(w)
end -- if you want to print each letter individually rather than sequences just remove the '+' sign </source>
The next example collects all pairs key=value from the given string into a table <syntaxhighlight lang="lua"> t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end </source> For this function, a '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.