Skip to content

Instantly share code, notes, and snippets.

@Nymphium
Created July 5, 2015 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nymphium/5ce12cf06e47ef80e369 to your computer and use it in GitHub Desktop.
Save Nymphium/5ce12cf06e47ef80e369 to your computer and use it in GitHub Desktop.
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