Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do you convert every 4 digits of a string into values?

Asked by 5 years ago

This might seem a little confusing but what I am trying to ask is if I have a string, for example I have "5,3,1,2,8,2,3,4". What I want is some code that will be able to take a sting of any length and return for example, that first digit of each of every four numbers. So what it would return in this case is 5 and 8. Keep in mind that this is a string, and that you will most likely need to find a way to count after every four commas, or something of the sort. Some script would be very helpful, but a written explanation is also fine.

1 answer

Log in to vote
2
Answered by
nilVector 812 Moderation Voter
5 years ago

What you are looking for is a string pattern that can find you all the numbers within a comma separated list of numbers stored in a string.

Utilizing string.gmatch, (which returns an iterator function that gives us the captures of our specified pattern each time it is called) with the %d+ pattern, we can accomplish something like this.

local str = "5,3,1,2,8,2,3,4"
local values = {} -- where you'll store every 4th number

local i = 0 -- to keep track of your place in the string
for v in str:gmatch("%d+") do -- for each number pattern found
    if i%4 == 0 then -- if it's the first in a list of four
        values[#values + 1] = tonumber(v)
    end
    i = i + 1
end
0
This really helps. Thanks! greenhamster1 180 — 5y
Ad

Answer this question