Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What does string.gmatch function represent?

Asked by
Arthim 0
5 years ago

I understand string.gmatch returns a function if the string is found within the given script. But what exactly does the function represent/do? Examples of what you can do with this would be helpful

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
5 years ago

string.gmatch, like pairs, returns an iterator. An iterator is a function that you can call over and over to give you more values.

For example, consider this:

for number in function() return math.random(1, 9) end do
    print(number)
    wait(1)
end

This will print random digits forever. This works because for loops repeatedly call the function after the in keyword.


The iterator you generally use the most in Lua is the one returned by pairs, which is functionally equivalent to the next function.

next gives you a key, value pair from a table:

local t = {a = "apple", b = "banana", c = "chocolate"}

print(next(t)) --> a apple
print(next(t, "a")) --> b banana
print(next(t, "b")) --> c chocolate

string.gmatch returns an iterator that will repeatedly extract matches from your string.

You can implement a function just like it yourself:

-- RETURNS an iterator function
function gmatch(s, p)
    local i = 1
    return function()
        local matchStart, matchEnd = s:find(p, i)
        if not matchStart then
            return nil
        end
        i = matchEnd + 1
        return s:sub(matchStart, matchEnd)
    end
end

for word in gmatch("Four score and seven years ago", "%a+") do
    print(word)
end

See the details of how a for loop works here.

Ad

Answer this question