lua-users home
lua-l archive

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


> In the following example there are two grammars, where `grammar2'
> is actually just a subset of `grammar1'. Is it possible to get rid
> of `grammar2'? That is, is it possible to change the initial rule
> of `grammar1' in between?
> 
> [...]

Yes and no. You cannot change the initial rule of a grammar, but you
can get rid of 'grammar2' using a very dirty hack:


local function select (t)
  -- succeeds only if extra argument to 'match' is equal to 't'
  return lpeg.Cmt(lpeg.Carg(1), (function (s, i, c)
                                   return (c == t)
                                 end))
end

rule_a = lpeg.V 'rule_a'
rule_b = lpeg.V 'rule_b'
rule_c = lpeg.V 'rule_c'

grammar1 = lpeg.P{
  -- new initial rule to select initial rule
  select('a') * rule_a + select('b') * rule_c,
  rule_a = '[' * rule_b * ']';
  rule_b = rule_c * (',' * rule_b)^0;
  rule_c = lpeg.R('az')/print;
}

lpeg.match(grammar1, '[a,b,c]', 1, 'a')
lpeg.match(grammar1, 'a', 1, 'b')


-- Roberto