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
(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
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
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).
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.