lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Jan 6, 2010 at 8:33 PM, duck <duck@roaming.ath.cx> wrote:
> Happy Summer, everyone :-)
>
> What is "Lua idiom" -- using the regular string library, not lpeg or any
> of the RE add-ons -- when doing string matching with alternative
> strings in it. For example, something like this:
>
>  "eat (green|yellow)? (bananas|apples) daily"
>
> (Assuming the round brackets are for alternation, not capture.)
>
> Of idiomatic Lua solutions, especially when rather more complex patterns
> are involved (notably with optional or repeated components, or with
> captures and backmatches), which way is fastest? Which is most elegant?
>
>
>

I haven't yet come across any particular idiom, beyond hand-crafting
it - writing a whole custom function that matches only part of the
string at a time. For example (since you said the brackets are for
alternation not capture, this returns either the whole string or nil):

 -- code start
 local colours = {green=1, yellow=1}
 local fruits = {bananas=1, apples=1}
 function custom_match(str)
   local pos = string.match(str, '^eat%s+()')
   if not pos then
     return nil
   end
   local word; word, pos = string.match(str, '^(%S+)%s+()', pos)
   if word and colours[word] then
     word, pos = string.match(str, '^(%S+)%s+()', pos)
   end
   if not (word and fruits[word] and string.match(str, '^daily$', pos)) then
     return nil
   end
   return str
 end
 -- code end

...You soon start to see why LPEG and other solutions are recommended
:) Though I do of course appreciate it's just not possible to use them
sometimes.

-Duncan