lua-users home
lua-l archive

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


> I saw someone say something about Lua patterns being very terse and
> confusing at first glance. I know I agree - I can't think of any
> easily readable regex patterns, so I hacked together this code. It
> adds a string.pattern field that is a literate programming interface.

I used something like this in a Lua assembler that I have been working on
on and off. Here's the relevant part of the code. Note how 'matches'
turns grammar rules into Lua patterns, caching the results. It understands
a small language with terminals 'w' for word, 'i' for integer, 'r' for rest
of the line. Everythng else is taken verbatim, except that space means
whitespace.

local PAT={
[' ']='%s+', ['-']='%-', ['w']='(%a+)', ['i']='([%a_][%w_]*)', ['r']='(.*)',
}
local function matches(s,p,f)
	if PAT[p]==nil then PAT[p]='^'..PAT[' ']..p:gsub('.',PAT) end
	local a,b,c=s:match(PAT[p])
	if not a then return false end
	if type(f)=='function' then f(a,b,c) end
	return f or true
end

local function parse(s)
	s=' '..s..' '
	return	matches(s,'$')
	or	matches(s,'--')
	or	matches(s,'DEFINE i r',dodefine)
	or	matches(s,'FUNCTION i',dofunction)
	or	matches(s,'END ',doend)
	or	matches(s,'EOF ','done')
	or	matches(s,'i: i r',dolabel)
	or	matches(s,'i r',doop)
	or	oops('bad line')
end