How do I get a number from a string?

Hi, can someone tell me how I can get a number from a string, for example, if i have “SecondaryHair1” How do I get the Number, in this case which is 1.

I would also like to know if it’s possible to split SecondaryHair1 to Secondary + Hair1 (if anyone could demonstrate this too i’d appreciate)

2 Likes

There are 2 solutions I can find, I’m not sure if they should be used but here they are:

  1. Separate each word & letter with a space and use string.split
    Separate each word and number like this: Secondary Hair 1
    Do something like this in your code:
local hair = script.Parent["Secondary Hair 1"]
local splitName = string.split(hair.Name, " ") --Returns an array of separated strings
local num = splitName[3] --Gets 1
  1. Use string.match
local hair = script.Parent.SecondaryHair1
local Find = string.match(hair.Name, "1") --Finds a match, if there's a match then it returns the match (In this case 1)

Learn more about string.split and string.match here:

NOTE: To turn it into a number, use tonumber:

local String = "1"
local Number = tonumber(String) --Turns "1", a string to 1, a number
2 Likes

Pretty simple actually.

To get a number from a string:

local str = "Hello World 10";

local numMatch = str:match("%d+"); -- matches all digits in the string --> 10

To get separated words:

local str = "HelloWorld10";

for match in str:gmatch("%u%l+") do
    print(match); --> Hello World
    -- Doesn't include digits
end

All this using string patterns.

17 Likes

To acquire the text of the number and the subtraction of digits, I combined two answers from here into one.

local numMatch = script.Parent.Buy.Text:match(%d+) --Here i have text: "Damage is: 10"
numMatch = tonumber(numMatch)
local value = numMatch + 5 --Here we can see 15
1 Like