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

bad argument #1 to 'gsub' (string expected, got user data), why?

Asked by
thePyxi 179
10 years ago

This script is to add commas in the number for cash, yet it always returns as a bad argument.

Here's the code:

1function 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
8end

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

01wait(1.2)
02 
03local plr=script.Parent.Parent.Parent.Parent.Parent
04local stats=plr:FindFirstChild('leaderstats')
05local dollars2=stats:FindFirstChild('Money')
06 
07 
08function 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
15end
View all 40 lines...

2 answers

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
10 years ago

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:

1while wait(.1) do
2    local dollars = force_decimal_places(dollars2.Value, 2)
3    dollars = addComma(dollars)
4 
5    script.Parent.Text = "$" .. dollars
6end

Or, more compactly and efficiently:

1function fixText()
2    script.Parent.Text = "$" .. addComma(force_decimal_places(dollar2.Value, 2))
3end
4dollars2.Changed:connect(fixText)
5fixText()
Ad
Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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.

0
The line breaks at the 4th line of function addComma(n) thePyxi 179 — 10y
0
Yes, because `f` is `n` which is `dollars2`. You should instead call it with `tostring(dollars2.Value)` so that `n` and `f` are strings. BlueTaslem 18071 — 10y

Answer this question