Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I simplify my string manipulation code snippet?

I was having a lot of trouble with this one piece of code that is supposed to fetch the price of items from similarly formatted text labels. While it works now, is there a way to simplify the code? Thanks.

The text being referenced is formatted like this: ItemName: $50

local price = string.sub(script.Parent.Parent.ItemName.Text,
	 string.sub(string.find(script.Parent.Parent.ItemName.Text, "%$"), 1, 2))
local price = tonumber(string.sub(price, 2))

1 comment

0

It looks very simple already.

1 answer

✓ Accepted answer

You can simplify it using string.match. If prices are expected to always be integers, you can do this:

local price = script.Parent.Parent.ItemName.Text:match('%$(%d+)');

However, if it's possible for them to have decimal places (in this example, up to two):

local price = script.Parent.Parent.ItemName.Text:match('%$(%d+%.?%d?%d?)');

Hope this helped.

2 comments

0

Thanks a lot. Can you explain exactly what the percentage signs and other special characters do in your argument for match()?

This discussion is preserved as it was. New answers, comments, and votes are closed.