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

How can I simplify my string manipulation code snippet?

Asked by
Klamman 220 Moderation Voter
7 years ago

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))
0
It looks very simple already. MrLonely1221 701 — 7y

1 answer

Log in to vote
0
Answered by
Pyrondon 2089 Game Jam Winner Moderation Voter Community Moderator
7 years ago

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.

0
Thanks a lot. Can you explain exactly what the percentage signs and other special characters do in your argument for match()? Klamman 220 — 7y
Ad

Answer this question