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

WaitForChild not working or not being used correctly?

Asked by 7 years ago

This is the script that does not work

local textBox = script.Parent:WaitForChild("textBox")

local function checkstr(str)
    local fullStr = ""
    for i in string.gmatch(str, "%d") do -- Only checks for numbers
        fullStr = fullStr..i
    end
    return fullStr
end

textBox.Changed:connect(function()
    local filter = checkstr(textBox.Text)
    textBox.Text = filter
end)

This is the script that works, however it does not allow a default text.

local textBox = script.Parent

local function checkstr(str)
    local fullStr = ""
    for i in string.gmatch(str, "%d") do -- Only checks for numbers
        fullStr = fullStr..i
    end
    return fullStr
end

textBox.Changed:connect(function()
    local filter = checkstr(textBox.Text)
    textBox.Text = filter
end)

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

If textBox is the Parent of the script then calling script.Parent:WaitForChild('textBox') won't work. WaitForChild(x) looks for a child called x within the instance you are using the function on. For example:

--I have a TextBox, inside the TextBox is a NumberValue called "Steve" and a script. Here is the script:

local steve=script.Parent:WaitForChild('Steve')
print(steve.Value)

If there is no child called 'Steve' inside my TextBox then I will never get to the run the rest of my script.

I recommend using the second script but declare the default text inside the script before the .Changed function so that the text must change before the .Changed function is even created. Also note that the .Changed function will run if ANYTHING dealing with the instance has changed such as it's been moved or a child added or it has a new parent. You can check what property was changed before continuing on with the rest of the script.

local textBox = script.Parent

local function checkstr(str)
    local fullStr = ""
    for i in string.gmatch(str, "%d") do -- Only checks for numbers
        fullStr = fullStr..i
    end
    return fullStr
end
textBox.Text="Type a Number Here" --Manually change the text first.  

textBox.Changed:connect(function(property)
    if property=="Text" then --Check that the text was specifically changed. 
        local filter = checkstr(textBox.Text)
        textBox.Text = filter
    end
end)

More on the .Changed function here

More on the :WaitForChild() function here

Ad

Answer this question