Instantly share code, notes, and snippets.

Embed
What would you like to do?
Toy calculator in Lua, version 1
function eval(num1, operator, num2)
if operator == '+' then
return num1 + num2
elseif operator == '-' then
return num1 - num2
elseif operator == '*' then
return num1 * num2
elseif operator == '/' then
return num1 / num2
else
return num1
end
end
spc = lpeg.S(" \t\n")^0
number = spc * lpeg.C(
lpeg.P('-')^-1 *
lpeg.R('09')^0 *
( lpeg.P('.') *
lpeg.R('09')^0
)^-1 ) * spc /
tonumber
expr = lpeg.P{
"EXPR";
EXPR = ( lpeg.V("TERM") * lpeg.C( lpeg.S('+-') ) * lpeg.V("EXPR") +
lpeg.V("TERM") ) / eval,
TERM = ( lpeg.V("FACT") * lpeg.C( lpeg.S('/*') ) * lpeg.V("TERM") +
lpeg.V("FACT") ) / eval,
FACT = ( spc * "(" * lpeg.V("EXPR") * ")" * spc +
number ) / eval
}
function repl(file)
file = file or io.input()
parser = expr
for line in file:lines() do
print(parser:match(line))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment