string.gmatch()

string.gmatch (s, pattern)pattern§6.4.1spattern

As an example, the following loop will iterate over all the words from string s, printing one per line:

1
2
3
4
s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
  print(w)
end

The next example collects all pairs key=value from the given string into a table:

1
2
3
4
5
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  t[k] = v
end

For this function, a caret '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.

doc_lua
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.