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

How would I make this work?

Asked by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
10 years ago
function Table(tble)
    return {
    tble = game:FindFirstChild(""..table);
    Child = function(chld)
        if tble:FindFirstChild(""..chld, true) then
        print(chld.Name)
        else
        print("Child Does Not Exist")
        end
    end
end

When I do..

Table("Workspace"):Child("Derp")

Then it errors even though Derp is a child of the workspace

1 answer

Log in to vote
2
Answered by
Destrings 406 Moderation Voter
10 years ago

There are a lot of errors on that snippet, so I'm going to recreate it following your idea, but I'm afraid you might not understand it

Table = setmetatable({
    Child = function(self, chld)
        assert(self.wrap, "Underlying object is nil") --Just a check
        local child = self.wrap:FindFirstChild(chld, true)
        if child then
            print(child.Name)
        else
            print("Child Does Not Exist")
        end
    end
    }, {
    __call = function(self, tble)
        return setmetatable({wrap = game:FindFirstChild(tble)}, {__index = Table})
    end}
)

Table("Workspace"):Child("Derp")

On side-note, in theory you are searching for descendants, not for childs.

I will try to keep it simple. We assign a variable Table (it's a bad practice to name variables like that) a table containing Child which is a method that searches for descendants of the object wrap field. We set to that table a metatable containing a __call metamethod wich returns a table with 'wrap' index set to the return of FindFirstChild called with the parameter and we set to that table a __index metamethod pointing to Table so that table has access to child, that way we can call it with the colon notation.

Consider looking into metatables and Object Oriented Programming in Lua if you didn't understand.

EDIT:

Fixed your idea which is more simple than mine

function Table(tble)
    return {
    tble = game:FindFirstChild(""..tble);
    Child = function(self, chld)
        if self.tble:FindFirstChild(""..chld, true) then
        print(self.tble:FindFirstChild(chld, true).Name)
        else
        print("Child Does Not Exist")
        end
    end}
end
Table("Workspace"):Child("BasePlate")

There are some bad practices there, like concatenating instead of just using the parameter, but I leave it like that and just fixed it.

Ad

Answer this question