Created
July 5, 2015 02:14
-
-
Save Nymphium/5ce12cf06e47ef80e369 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import P, S, V, R, C, Ct, match from require "lpeg" | |
Space = S' \n\t'^0 | |
Num = C(P'-'^-1 * R'09'^1 ) * Space | |
Term = C(S'+-') * Space | |
Fact = C(S'*/%') * Space | |
Open = '(' * Space | |
Close = ')' * Space | |
G = P{ | |
"Exp" | |
Exp: Ct(V'Term' * (Term * V'Term')^0) | |
Term: Ct(V'Fact' * (Fact * V'Fact')^0) | |
Fact: Num + Open * V'Exp' * Close | |
} | |
G = Space * G * -1 | |
eval = (x) -> | |
local ret_num | |
if type(x) == "string" | |
-- tonumber x | |
ret_num = tonumber x | |
else | |
op1 = eval x[1] | |
for i = 2, #x, 2 | |
op = x[i] | |
op2 = eval x[i + 1] | |
switch op | |
when '+' op1 += op2 | |
when '-' op1 -= op2 | |
when '*' op1 *= op2 | |
when '/' op1 /= op2 | |
ret_num = op1 | |
ret_num | |
eval_exp = (s) -> | |
t = match(G, s) | |
if not t | |
error "Syntax error", 2 | |
eval t | |
repl = -> | |
while true | |
io.write "> " | |
l = io.read! | |
if not l | |
break | |
print eval_exp l | |
repl! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment