How do i split a 5 digit number string into individual numbers?

Basically im trying to figure out how to split 5 digit numbers into their own number
ex: 18563 = 1,8,5,6,3

currently i have attempted to convert it to a string instead of being a number value to see if i could split it but i cant figure it out. I need it to be in a form that each individual number can be set as their own variable. Something like this
image
(this part is for something else this is just an example)
i would appreciate the help!

local number = "12345"

local result = {}

for i = 1, #number do
	table.insert(result, tonumber(number:sub(i, i)))
end

local num1 = result[1]
local num2 = result[2]
local num3 = result[3]
local num4 = result[4]
local num5 = result[5]

You can also use string.gmatch but this is the way I would do it.

local s1, s2, s3, s4, s5 = unpack(tostring(number):split(''))

try this. first it converts the number to a string, then splits it into a table of its 5 characters. unpack turns that table into a tuple which you can assign to 5 variables

2 Likes

You could also do this:

local number = "12345"

local result = {}

for i = 1, #number, 1 do
	table.insert(result, i)
end

local get = table.concat(result, ",")

print(get)

The output would print “1,2,3,4,5”.

1 Like
function Convert(Number)
    return table.concat(string.split(tostring(Number), ""), ",")
end

print(Convert(123)) -- 1,2,3

Type coercion and gmatch so the number doesn’t have to start as a string.

local fullNumber = 18563
local numbers = table.create(8) -- 2^ rule

for number in tostring(fullNumber):gmatch("%d") do
    table.insert(numbers, tonumber(number))
end

print(table.concat(numbers, ", ")) --> 1, 8, 5, 6, 3
2 Likes

You could also use string.byte to achieve this by extracting each character from the first position to fifth and then do some ASCII encoding-related manipulation (subtract by 0x30 because that is the ASCII code for 0 and 0x31 is the ASCII code for 1, etc).

Example snippet:

local d0, d1, d2, d3, d4 = string.byte("12345", 1, -1)

print(string.char(d0, 0x2C, 0x20, d1, 0x2C, 0x20, d2, 0x2C, 0x20, d3, 0x2C, 0x20, d4)) -- 1, 2, 3, 4, 5

d0 -= 0x30
d1 -= 0x30
d2 -= 0x30
d3 -= 0x30
d4 -= 0x30

print(d0, d1, d2, d3, d4) -- 1 2 3 4 5

This method and all of it above relies on tostring - alternatively you could use floor/truncate (assuming the values aren’t negative) division and modulo with the denominator being 10**i where i is the position of the digits (from units to ten-thousandths) of the number (and is zero-based) to get the digits.

VM-native “tuples” does not exist in Lua(u). When a function returns multiple value in Lua(u), the function bona fide returns multiple value - no abstract data structures are used.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.