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

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

Asked by
thePyxi 179
9 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:

function addComma(n)
    local f,k = n
    while (true) do
        f,k = string.gsub(f,"^(-?%d+)(%d%d%d)","%1,%2")
        if (k == 0) then break end
    end
    return f
end

It breaks on line 4 saying: bad argument #1 to 'gsub' (string expected, got user data)

Can someone help me with this?

This is the entire code, which is inside a TextLabel

wait(0.6)

local plr=script.Parent.Parent.Parent.Parent.Parent
local stats=plr:FindFirstChild('leaderstats')
local dollars2=stats:FindFirstChild('Money')

function addComma(n)
    local f,k = n
    while (true) do
        f,k = string.gsub(f,"^(-?%d+)(%d%d%d)","%1,%2")
        if (k == 0) then break end
    end
    return f
end



function force_decimal_places(num, places)
    if type(num) ~= 'number' or type(places) ~= 'number' then
        return 'NaN' --not a number
    end
    local mult = 10^(places or 0) --set up rounding places
    num = tostring( math.floor(num * mult + 0.5) / mult ) --round
    local dot = string.find(num, '%.')
    if not dot then --easily add zeros to an integer
        num = num..'.'..string.rep('0', places)
    else --some after decimal?
        local after = string.sub(num, dot + 1)
        if after ~= places then --if it doesn't already round to exact places
            num = num..string.rep('0', places - #after)
        end
    end

    return num --returns a string (otherwise the zeros would get truncated)
end

while wait(0.1) do
dollars2 = addComma(dollars2)
local dollars = force_decimal_places(dollars2.Value, 2)
script.Parent.Text = '$'..dollars 
end
0
looks like f is a userdata value instead of a string. You'll have to post more of the code for me to help you aquathorn321 858 — 9y
0
Like aquathorn321 mentioned, the problem is probably in the part that calls the function rather than the function itself. Could you post the code that uses `addComma(...)`? noliCAIKS 210 — 9y

1 answer

Log in to vote
0
Answered by 9 years ago

You probably used the TextLabel as your variable, rather then TextLabel.Text

Ad

Answer this question