Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

What does string.gmatch function represent?

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

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.