使用Lua语言的Corona - 将文本转换为公式

有没有办法将字符串 "1 + 2 * 3" 转换成变量中的 1 + 2 * 3 呢?数字并不重要,我只是想弄清楚如何让 Lua 将字符串计算成数字。tonumber() 不能用于此。

点赞
用户1442917
用户1442917

如果你只需要简单的计算,那么像这样的函数可能会有用:

function calculator(expression)
  expression = expression:gsub("%s+", "")
  while true do
    local head, op1, op, op2, tail = expression:match("(.-)(%d+)([%*/])(%d+)(.*)")
    if not op then break end
    expression = head .. tostring(op == '*' and op1 * op2 or op1 / op2) .. tail
  end
  while true do
    local head, op1, op, op2, tail = expression:match("(.-)(%d+)([%+%-])(%d+)(.*)")
    if not op then break end
    expression = head .. tostring(op == '+' and op1 + op2 or op1 - op2) .. tail
  end
  return tonumber(expression)
end

function calculator(expression)
  expression = expression:gsub("%s+","")
  local n
  repeat
    expression, n = expression:gsub("(%d+)([%*/])(%d+)",
      function(op1,op,op2) return tostring(op == '*' and op1 * op2 or op1 / op2) end, 1)
  until n == 0
  repeat
    expression, n = expression:gsub("(%d+)([%+%-])(%d+)",
      function(op1,op,op2) return tostring(op == '+' and op1 + op2 or op1 - op2) end, 1)
  until n == 0
  return tonumber(expression)
end

print(calculator('1 + 2') == 3)
print(calculator('1+2+3') == 6)
print(calculator('1+2-3') == 0)
print(calculator('1+2*3') == 7)
print(calculator('1+2*3/6') == 2)
print(calculator('1+4/2') == 3)
print(calculator('1+4*2/4/2') == 2)
print(calculator('a+b') == nil)

有两个名为 calculator 的函数,它们以稍微不同的方式完成相同的任务:它们将表达式折叠到只有一个数字为止。 "1+2*3/6" 被转换为 "1+6/6",然后变成 "1+1",最后变成 "2",作为数字返回。

2015-12-08 05:29:51