Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How would I make this work?

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

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.