2015-12-07 19 views
2

有沒有辦法在變量中將「1 + 2 * 3」轉換爲1 + 2 * 3?數字並不重要,我只是想弄清楚如何讓Lua將一個字符串計算爲一個數字。 tonumber()不適用於此。Corona with Lua - 將文本轉換爲公式

+0

看來你不能使用'loadstring'。純Lua中的解決方案將取決於您打算使用的表達式的複雜程度。 – lhf

+0

如果您可以使用LPeg,請嘗試http://rosettacode.org/wiki/Arithmetic_evaluation#Lua。 – lhf

+0

昨天晚上我開始閱讀LPeg,但沒有得到嘗試的機會。謝謝你的評論。 –

回答

2

如果您只需要簡單的操作,這樣的事情可能工作:

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+6/6",然後變成"1+1",最後變成"2",它作爲數字返回。

+1

這很好。謝謝! –

+0

我在第二個實現(',1'到'gsub')上添加了一個調整來解決分割或減法操作序列的問題(以強制執行從左到右的處理)。 –