This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
W00dyR's profile picture

[Lua] string.gmatch quick question

Started by W00dyR, 19 May 2013 - 03:37 PM
W00dyR #1
Posted 19 May 2013 - 05:37 PM
Hey guys,

I've been starting to learn more about this function and the stuff it does, but I still don't get a part of it:

For example in this:


for blabla in string.gmatch(text, "%w+") do
	print(blabla)
end

What does the "%w+" exactly mean? In other scripts I've seen things like "[^%s]+" or even "%a+".

I see this differ a lot everywhere, and on the lua manuals I can't really find the origin of the choice of what you type there :/

I do realize that this is a kind of search pattern?

Thanks ahead!
Sammich Lord #2
Posted 19 May 2013 - 05:39 PM
This is a pretty good tutorial I found. http://www.wowwiki.com/Pattern_matching
W00dyR #3
Posted 19 May 2013 - 05:44 PM
This is a pretty good tutorial I found. http://www.wowwiki.c...attern_matching

Ah that is exactly what I was looking for, thanks :)/>

So if I understand correctly, it's a combination of symbols which all represent a part of the pattern you assign the string.gmatch to look for? So for example if I have a simple line to split, containing both numbers and letters, I start with "%w" so it does both letters and numbers. Then I add "+" to it so it will not stop after its first match? So for what I described "%w+" would work the best?
theoriginalbit #4
Posted 20 May 2013 - 12:39 AM
if you're wanting to do a simple string split then a pattern like so would work fine
self:gmatch('[^'..patt..']+')
where patt is the separator. Using the above pattern in a for loop is the simplest option for splitting a string by a common separator.