2

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
3
  • 1
    See stackoverflow.com/questions/945731/… Commented Nov 22, 2016 at 14:24
  • Works fine here with Lua 5.3.3 Commented Nov 22, 2016 at 14:29
  • I use Windows, and the latest version I found is Lua 5.1 Commented Nov 22, 2016 at 14:46

1 Answer 1

3

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
2
  • 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? Commented Nov 22, 2016 at 15:12
  • "How to install Lua package in redis" is a separate question. Sorry, I know nothing about redis. Commented Nov 22, 2016 at 16:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.