Lua-Pattern - Evaluate conditional expression
snippet in lua

Lua-Pattern - Evaluate conditional expression

user8775

local lpeg = require"lpeg"
local P, V = lpeg.P, lpeg.V

local True = function() return true end
local False = function() return false end
local Not = function(a) return not a end
local Eq = function(a,b) return a == b end
local And = function(a,b) return a and b end
local Or = function(a,b) return a or b end

local grammar = P{
    "cond",
    cond = (V"x")
         + (V"x" * "==" * V"x") / Eq
         + (P"!{" * V"cond" * P"}") / Not
         + (P"{" * V"cond" * P"&&" * V"cond" * P"}") / And
         + (P"{" * V"cond" * P"||" * V"cond" * P"}") / Or,
    x = P"1" / True
      + P"0" / False
      + P"boolean:true" / True
      + P"boolean:false" / False
}

local eval = function(exp)
    return grammar:match(exp)
end

print(eval('{{1||boolean:false}&&{boolean:true&&!{boolean:false}}}'))