String.gsub producing unexpected results

The string.gsub() function is producing unexpected and undesired effects for me. What I’m attempting to do is take a SoundID string from a table, remove the rbxassetid:// from the string, then turn it into a number. My “songs” table currently looks like this:

local songs = {
	{"rbxassetid://1843608270", 2},
	{"rbxassetid://1839901023", 0.75},
	{"rbxassetid://1848051253", 1},
	{"rbxassetid://1847123829", 0.8},
	{"rbxassetid://1848051244", 1.75}
}

In a function, the variable s is the chosen song to play. To remove the rbxassetid:// from the string, I’m using the function string.gsub(songs[s][1], "rbxassetid://", ""). I then convert it to a number with the tonumber() function. I’m pretty sure that’s the way you do it, but the results say otherwise.

When attempting this, I get the error: invalid argument #2 to 'tonumber' (base out of range). Strange. For testing purposes, I set up two print lines. One prints songs[s][1], while the other prints the result of the string.gsub(songs[s][1], "rbxassetid://", "") line mentioned earlier. Shown below are the results:

image

Where in the world is that extra 1 coming from in the gsub results? If anyone could explain why that’s appearing, please let me know.

PS - I am well aware of a better way to do this where I store the asset ID number values in the table instead, then add “rbxassetid://” to them later when putting the id in a Sound. I’ll be changing the script to do this later, I just want to know why string.gsub did whatever it did here.

In Lua, the function string.gsub returns two values, the modified string and the number of substitutions made. If you’re passing the result of string.gsub to another function like tonumber, it uses only the first returned value.

Actually, tonumber has a widely unknown second argument that’s used to set the base of which the number is converted to. One substitution is made, so the remaining string is forwarded to tonumber and so is that substitution count of 1. This requests that the song ID be cast to base 1. The solutions here are as follows,

  1. Use string.match with the pattern %d+$ instead of string.gsub
  2. Store the result of string.gsub in a single variable and pass that variable to tonumber or wrap the result of the function call in parentheses. This cuts off the rest of the tuple