From ab493693a98b3e496bf865ecbaa3985162f57987 Mon Sep 17 00:00:00 2001 From: Connor Olding Date: Sun, 27 Nov 2016 21:17:42 -0800 Subject: [PATCH] add support for variables in expressions --- lips/Expression.lua | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lips/Expression.lua b/lips/Expression.lua index 4d4cfcb..46ed0bb 100644 --- a/lips/Expression.lua +++ b/lips/Expression.lua @@ -4,6 +4,9 @@ local path = string.gsub(..., "[^.]+$", "") local Base = require(path.."Base") local Expression = Base:extend() +function Expression:init(variables) + self.variables = variables or {} +end Expression.precedence = { -- python-ish precedence @@ -80,6 +83,7 @@ Expression.binary_ops = { local operators = {} local operators_maxlen = 0 do + -- reorder operators so we can match the longest strings first for k, v in pairs(Expression.precedence) do if operators[#k] == nil then operators[#k] = {} @@ -169,6 +173,13 @@ function Expression:lex1(str, tokens) elseif consider_operator() then insert(tokens, {type='operator', value=considered}) consume(#considered) + elseif consider('%w+') then + local num = self.variables[considered] + if num == nil then + return 'undefined variable "'..considered..'"' + end + insert(tokens, {type='number', value=num}) + consume(#considered) else local chr = rest:sub(1, 1) return "unexpected character '"..chr.."'"..here