Having an issue with my logic on string manipulation

Hey, so I’m trying to develop a function that takes in a string of numbers, separates each pair of numbers, and returns a table containing actual integers.

To clarify further, I pass in arguments such as…

1,2,4,16,24

In other words, a string of numbers separated by commas. I then call this function to separate that string into pairs of numbers and then return the table of the real numbers.

Here’s my code:

local function Get_Ranks(str)
     local numbers = {}
     local current_number = ""
     for i = 1,#str do
	if str:sub(i,i) == "," then
		table.insert(numbers, tonumber(current_number))
		current_number = ""
	else
		current_number = current_number..str:sub(i,i)
	end
    end
    return numbers
end

It works quite nicely, although I can’t figure out why it always cuts off the last number at the end of the string. Any help appreciated, thanks!

1 Like

Whoops, I figured it out.

The issue was if the current character of the string was not a comma, it kept going forever, and the key here is that there’s not another comma at the end of the string, so that number that was being made never got inserted into the table.

:slight_smile:

string.split is your friend.

local ranks = string.split(str, ",")
for _, rank in ipairs(ranks) do
    print(rank) -- convert each rank to a number if necessary.
end
1 Like