for i,v in pairs(GUI.InventorySlotsBackground:GetChildren()) do -- loop through the inventory slots
if v:IsA("ImageLabel") and v:FindFirstChildWhichIsA("TextLabel") then -- if v is an inventory slot, then
local Amount = v:FindFirstChildWhichIsA("TextLabel") -- text label is equal to the amount of items the player has
if tonumber(string.gsub(Amount.Text, "x", nil)) then
print(tonumber(string.gsub(Amount.Text, "x"), nil))
end
end
end
task.wait()
I made a script which is meant to be removing the letter “x” from the TextLabel’s text, and printing it out. The text is equal to the amount of items a player has, but has an X at the end. For example, if the player has 30 wood, the text would say “30x”.
The 3rd argument has to be a replacement for the letter x, which I don’t want, so I put nil. This is giving an error: invalid argument #3 to 'gsub' (string/function/table expected, got nil)
gsub returns a string and a number
string is the new created string
number is amount of changes
all you need is this
print(Amount.Text)
local s = string.gsub(Amount.Text, "x", "")
if tonumber(s) < 0 then
print(s)
end
the error tells you that you used an out of range baste tonumber(string, base)
gsub returns here 69 and 1 because we change one x to empty so what you did is this tonumber(“69”, 1)
which is invalid
string.gsub returns two values, the first is the filtered string, and the second is the amount of replacements made. You are giving the tonumber() function 2 variables, not 1.
I would also recommend running the string.lower() function on Amount.Text to turn and uppercase X into a lowercase x to filter both types of xs on the string.gsub() function.
I also added the or 1 in the event that the string the player entered is not a number which would cause the script to error because nil < 0 is not possible.
local FilteredText = string.gsub(string.lower(Amount.Text), "x", "")
if (tonumber(FilteredText) or 1) < 0 then
--// Your Code Here
end
Use string.find or string.match, both return ‘nil’ if the search pattern isn’t found within the subject string.
local Amount = v:FindFirstChildWhichIsA("TextLabel") -- text label is equal to the amount of items the player has
if Amount then --Check if 'Amount' exists.
local Number = string.match(Amount.Text, "^(%d+)x$") --Grab the number part from the text label's name.
if Number then --Make sure 'Number' is not 'nil'.
print(Number) --Output the value of 'Number'.
end
end