2016-11-22 47 views
2

我在Lua這個簡單的腳本:Lua的錯誤「試圖對字符串值執行算術」

local function addDigits(n) 
    n=n.."" 
    local s1=0 

    for i=1,n:len() do 
     s1=s1+n:sub(i,i) 
    end 
    return s1 
end 

如果我把它叫做小值,

addDigits(12345678123456) 

它表現良好。但如果我用較大的值調用它,如

addDigits(1234567812345678) 

我收到「嘗試對字符串值執行算術運算」。

我試過用「toNumber」,

s1=s1+tonumber(n:sub(i,i)) 

,但我收到「試圖在零值進行算術」。

我對Lua很新,所以任何幫助都會很棒!謝謝!

+1

查看http://stackoverflow.com/questions/945731/what-is-the-maximum-value-of-a-number-in-lua –

+0

在這裏用Lua工作得很好5.3.3 –

+0

我使用Windows,並且我發現的最新版本是Lua 5.1 –

回答

3

數量12345678123456變得1.2345678123457e+015當被轉換爲字符串,所以你有問題,s1=s1+"."s1=s1+"e"s1=s1+"+"

+0

我嘗試在這裏使用這個庫:http://oss.digirati.com.br/luabignum/bn/,但我使用redis-cli,並且我不能使用require。所以,我只是在我的目錄中添加了BigNum.lua,但仍然無法使用該庫。任何建議? –

+0

「如何在redis中安裝Lua軟件包」是一個單獨的問題。對不起,我對redis一無所知。 –