lua-users home
lua-l archive

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


Mike Spencer wrote:

but i would also like to know how to parse floating point using lex

Try this:

$ cat test
1
1.0
.01
x -1 junk
-.01
-1.68587e-007
Particles = 100
Emitter.delay = 0.001
Emitter.delayFuzz = 0

$ lua lex_number.lua test
1
number='1' start=1 end=2

1.0
number='1.0' start=1 end=4

.01
number='.01' start=1 end=4

x -1 junk
number='-1' start=3 end=5

-.01
number='-.01' start=1 end=5

-1.68587e-007
number='-1.68587e-007' start=1 end=14

Particles = 100
number='100' start=13 end=16

Emitter.delay = 0.001
number='0.001' start=17 end=22

Emitter.delayFuzz = 0
number='0' start=21 end=22


$ cat lex_number.lua

function number(str)
 local s = string.find(str, '%-?%.?%d')
 if s then
   local b,e1,e2,e3,e4
   b,e1 = string.find(str, '^%-?%d+%.%d*', s)  -- D+ . D*
   b,e2 = string.find(str, '^%-?%d*%.%d+', s)  -- D* . D+
   b,e3 = string.find(str, '^%-?%d+', s)       -- D+
   local c = e1 or e2 or e3
   b,e4 = string.find(str, '^[Ee][+-]?%d+', c+1)
   local e = e4 or c
   return string.sub(str, s, e), s, e+1
 end
end

function printf(...) io.write(string.format(unpack(arg))) end

local filename = arg[1]

for l in io.lines(filename) do
 print(l)
 local n, s, e = number(l)
 if n then
   printf("number='%s' start=%d end=%d\n\n", n, s, e)
 end
end

- Peter Shook

_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail