Skip to content

Instantly share code, notes, and snippets.

@weshoke
Created October 21, 2013 01:55
Show Gist options
  • Select an option

  • Save weshoke/7077605 to your computer and use it in GitHub Desktop.

Select an option

Save weshoke/7077605 to your computer and use it in GitHub Desktop.
Parsing integers with LPEG in Lua
local lpeg = require"lpeg"
local P, R, S = lpeg.P, lpeg.R, lpeg.S
-- Any non-zero digit: (R stands for Range)
local nonzero = R"19"
-- Only zero: (P stands for Pattern)
local zero = P"0"
-- Any digit:
local digit = R"09"
-- Match a sqeuence of one or more numbers not starting with zero (aka positive numbers)
local positive = nonzero * (zero + nonzero)^0
-- Match the natural numbers (positive numbers including zero)
local natural = zero + positive
-- Match all integers (including negative numbers)
local integer = P"-"^-1 * natural * P(-1)
print(integer:match"1") --> '2', match successful
print(integer:match"0") --> '2', match successful
print(integer:match"109234") --> '7', match successful
print(integer:match"-10") --> '4', match successful
print(integer:match"-0") --> '3', match successful
print(integer:match"012") --> 'nil', match unsuccessful
print(integer:match"2a12") --> 'nil', match unsuccessful
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment