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
9 years ago

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

1local newActualPad = closeByCheck(currentPly):Clone()

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

01local closeByCheck = function(ply)
02    local part
03    print("closeByCheck")
04    local signal
05    signal = ply:FindFirstChild("Right Leg").Touched:connect(function(otherPart)
06    print("Touched")
07    print(otherPart.Parent)
08    if otherPart.Parent == game.Workspace.Grid then
09        print("Part is grid")
10        if (ply.HumanoidRootPart.Position - otherPart.Position).magnitude < startRange then
11            print("Part is close")
12            part = otherPart
13            print(part.Name)
14        end
15    end
16    signal:disconnect()
17 
18end)
19       return part
20end

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 — 9y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 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:

1repeat
2    wait()
3until part
4return 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