lua-users home
lua-l archive

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


Cue the zealot with the LPeg answer in 3...2...1..


local lpeg = require"lpeg"

local P, R, C = lpeg.P, lpeg.R, lpeg.C

local integer = R("09")^1
local mant  = P"." * integer
local number = C(integer * (mant + -1))
local trimmed_mant = P"." * (R"09"^1 - (P"0"^0 * -1))
local trimmed_number = C(integer * (P"." * R"09" * (R"09"- (P"0"^0 * -1))^0)^-1)
local n1 = "123.450000000" 
local n2 = "1234500"
local n3 = "12345.00" 

print(trimmed_number:match(n1))
--> 123.45

print(trimmed_number:match(n2))
--> 1234500

print(trimmed_number:match(n3))
--> 12345.0


On Fri, Aug 30, 2013 at 4:10 PM, Geoff Smith <spammealot1@live.co.uk> wrote:
Hi
 
Wow, you guys are quick. Three working solutions and a debate about the subtleties of a solution, all in the time I would be chewing my pencil and staring at a blank sheet of paper Emoji
 
I tried all 3 solutions, they all work fine.  I am still trying to digest how they all work though. Its a very useful example in learning how pattern matching works,  it would be a good and practical example problem for the Lua wiki page.
 
Thanks to everyone for your help
 
Regards Geoff