How do I use string.gmatch?

Can I get an example?
I’m still confused.

1 Like

You can find a lot of examples online with a quick Google search:

Example:

for word in string.gmatch("Hello Lua user", "%a+") do print(word) end

Returns

Hello
Lua
user

Source: lua-users wiki: String Library Tutorial

Hope this helps.

6 Likes

string.gmatch returns the next capture from a string each time it is called. You can set what you want to be captured each time using string patterns. Here is a quick example:

local String = "Hello this is a string"

local Match = string.gmatch(String,".") -- The second argument in this is the string pattern

print(Match()) -- Prints the next capture. In this case it will be "H"
print(Match()) -- Prints the next capture. In this case it will be "e"

In the example above, each timeMatch() is called it will return the next letter in the string.

9 Likes

[quote=“Solved by [redacted] in post #2, post:2, topic:313386”]
for word in string.gmatch("Hello Lua user", "%a+") do print(word) end
[/quote]

How would i get the index number from the loop? Like you’d see on normal for loops.

for index, child in ipairs(Map) do 
    print(index) 
end

Count it yourself.

local i = 0
for word in string.gmatch("Hello Lua user", "%a+") do
    i = i + 1
    print(i, word)
end
3 Likes

Thanks, i was just hoping there was an index variable somewhere in the loop that i didn’t know about.

2 Likes

what is = in the character class???