lua-users home
lua-l archive

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


On Mon, Dec 13, 2010 at 11:03:45PM +0200, Luiz Henrique de Figueiredo wrote:
> About s[i]:
> 
> > Funny, but I found myself wanting to type exactly that not an hour ago.
> > I remembered that it wasn't the "Lua way," though, and stopped myself in
> > time.
> > 
> > Would be nice if it worked, though.
> 
> It'd be nice, and it can be made to work with a suitable change in __index
> in the string metatable, but it does not seem to be as useful as it promises:
> how often do you scan a string byte by byte? 

I happen to be working on a such a project right now!   In the PMX
language for music notation, a note is described by a string like
    a45fd+.4
which translates to "the note 'a', a quarter-note long, in the fifth
octave, flattened, dotted, print the dot .4 units to the right".  
Any permutation of the symbols in which 'a' is first, '4' comes before 
'5' and 'd+.4' remains together but is not followed by a digit, means 
the same.  There are about 20 possible such subfields.  Don't blame
me for the syntax: it was invented to make life easier for the musician,
not for the programmer.

I use a finite machine approach.  Describe the syntax with tables of 
tables of functions:

note = { ['4'] = digit, f = accidental, d = dots, ... }
parse = { a=note, b=note, ... }

and later the complete parser is (using the more easily implemented 
w(p) rather that w[p]):
    p=2;  while p<=#w do parse[w(1)][w(p)](w) end
each function like 'dots' advancing the position p.  These functions
make use of single-character indexing too.

Dirk