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

My function seems not to return it's object, turns out nil, what's the problem?

Asked by
Xianon 105
8 years ago

Ok, first i call my function to return an object so i can clone it:

local newActualPad = closeByCheck(currentPly):Clone()

closeByCheck has to return me an object so i can clone it

local closeByCheck = function(ply)
    local part 
    print("closeByCheck")
    local signal
    signal = ply:FindFirstChild("Right Leg").Touched:connect(function(otherPart)
    print("Touched")
    print(otherPart.Parent)
    if otherPart.Parent == game.Workspace.Grid then
        print("Part is grid")
        if (ply.HumanoidRootPart.Position - otherPart.Position).magnitude < startRange then
            print("Part is close")
            part = otherPart
            print(part.Name)
        end
    end
    signal:disconnect()

end)
       return part
end

When i run it, closeByCheck returns me nothing, and when the script is gonna clone, error, attempt to index a 'nil'

1
It's most probably something with the 'if' at line 10, because if the if goes false then the part never gets defined, so it would return nil sigve10 94 — 8y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

A connection doesn't take time. Your code executes like this:

  1. part = nil
  2. start listening for a touched
  3. return part

Since part (2.) is done immediately, your closeByCheck might as well be return nil.


You could wait until part is not nil, for example:

    repeat
        wait()
    until part
    return part

Though I'm not sure if a design that waits for a contact makes sense, since it could be a very long time before anything touches this.

Ad

Answer this question