This script is to add commas in the number for cash, yet it always returns as a bad argument.
Here's the code:
1 | function addComma(n) |
2 | local f,k = n |
3 | while ( true ) do |
4 | f,k = string.gsub(f, "^(-?%d+)(%d%d%d)" , "%1,%2" ) |
5 | if (k = = 0 ) then break end |
6 | end |
7 | return f |
8 | end |
It breaks on line 4 saying: bad argument #1 to 'gsub' (string expected, got userdata)
Can someone help me with this?
This is the entire code, which is inside a TextLabel
01 | wait( 1.2 ) |
02 |
03 | local plr = script.Parent.Parent.Parent.Parent.Parent |
04 | local stats = plr:FindFirstChild( 'leaderstats' ) |
05 | local dollars 2 = stats:FindFirstChild( 'Money' ) |
06 |
07 |
08 | function addComma(n) |
09 | local f,k = n |
10 | while ( true ) do |
11 | f,k = string.gsub(f, "^(-?%d+)(%d%d%d)" , "%1,%2" ) |
12 | if (k = = 0 ) then break end |
13 | end |
14 | return f |
15 | end |
If you try to set dollars2
to the value returned by addComma
, you lose the reference to the Money ValueObject, breaking the script.
addComma
expects a string. First, you set f = n
on the first line. Then, you call gsub
on f
. If f
isn't a string, this doesn't work.
Additionally, force_decimal_places
expects a number, since you perform math on it. To fix these, you need to change your loop:
1 | while wait(. 1 ) do |
2 | local dollars = force_decimal_places(dollars 2. Value, 2 ) |
3 | dollars = addComma(dollars) |
4 |
5 | script.Parent.Text = "$" .. dollars |
6 | end |
Or, more compactly and efficiently:
1 | function fixText() |
2 | script.Parent.Text = "$" .. addComma(force_decimal_places(dollar 2. Value, 2 )) |
3 | end |
4 | dollars 2. Changed:connect(fixText) |
5 | fixText() |
f
is dollars
, since that's the parameter you passed. dollars2
is a userdata, as it says. That means it's a ROBLOX object.
Instead, use addComma( tostring(dollars2.Value) )
to get the value of that object, and apply string processing to it. I'm unsure why you'd overwrite the dollars2
variable with that string, though, since that will prevent the value from updating in the future.