I have this simple script in 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
If I call it with small values, as
addDigits(12345678123456)
it performs well. But if I call it with larger values, as
addDigits(1234567812345678)
I receive "attempt to perform arithmetic on a string value".
I've tried with "toNumber",
s1=s1+tonumber(n:sub(i,i))
but I recieve "attempt to perform arithmetic on a nil value".
I am very new to Lua, so any help will be great! Thanks!
asked Nov 22, 2016 at 14:14
-
1See stackoverflow.com/questions/945731/…David Crayford– David Crayford2016年11月22日 14:24:41 +00:00Commented Nov 22, 2016 at 14:24
-
Works fine here with Lua 5.3.3Uli Schlachter– Uli Schlachter2016年11月22日 14:29:15 +00:00Commented Nov 22, 2016 at 14:29
-
I use Windows, and the latest version I found is Lua 5.1Adrian Kreator– Adrian Kreator2016年11月22日 14:46:39 +00:00Commented Nov 22, 2016 at 14:46
1 Answer 1
The number 12345678123456
becomes 1.2345678123457e+015
when being converted to a string, so you have problem with s1=s1+"."
, s1=s1+"e"
and s1=s1+"+"
.
answered Nov 22, 2016 at 14:28
-
I try to use this library here: oss.digirati.com.br/luabignum/bn, but I use the redis-cli, and I cannot use require. So, I just added BigNum.lua in my directory, but still I cannot use the library. Any suggestion?Adrian Kreator– Adrian Kreator2016年11月22日 15:12:36 +00:00Commented Nov 22, 2016 at 15:12
-
"How to install Lua package in redis" is a separate question. Sorry, I know nothing about redis.Egor Skriptunoff– Egor Skriptunoff2016年11月22日 16:28:06 +00:00Commented Nov 22, 2016 at 16:28
lang-lua