-4

So i have this number 1234567890 declared as this.

local num = 1234567890; 

and now i what to add those numbers together 2+4+6+8+0 so would i go about this?

Firas Assaad
  • 25,006
  • 16
  • 61
  • 78
Beri
  • 245
  • 2
  • 17
  • Can you please be elaborate? These seem to be two unrelated things. – legends2k Apr 07 '14 at 21:52
  • 2
    possible duplicate of [Sum of the digits of an integer in lua](http://stackoverflow.com/questions/22180828/sum-of-the-digits-of-an-integer-in-lua) – p.s.w.g Apr 07 '14 at 21:52
  • Why did you repeat yourself 3 times? Why do you say "I want to add *those* numbers" then give an example using different numbers? – Mud Apr 07 '14 at 21:53
  • If you want to add all the digits of `1234567890`, please say so. If not, please explain exactly what you're trying to do and clarify how it's related to `1234567890`. At stands now, `print(20)` would answer your question, but i don't think that's what you had in mind. – Keith Thompson Apr 07 '14 at 22:16
  • I want to add every second digit together. – Beri Apr 07 '14 at 23:36
  • "Every second digit" from the left? Or, the first, third, ... from the right? That would make a difference if there are an odd number of decimal digits. – Tom Blodget Apr 08 '14 at 16:31

1 Answers1

3

Try this:

local num = 1234567890
local sum = 0
for a,b in tostring(num):gmatch("(.)(.)") do
    sum=sum+tonumber(b)
end
print(sum)
lhf
  • 70,581
  • 9
  • 108
  • 149