How do I insert instantes into metatables?

  1. What do you want to achieve?
    I want to insert a ModuleScript into a metatable and be able to change its properties.

  2. What is the issue?
    I made a function that takes modules from a folder and sets them to a table then I set the metatable. I saw that it wasn’t working so I unpacked the table and then printed it and the table was empty. (No modules).

  3. What solutions have you tried so far?
    There’s nothing about instances into metatables on DevForum.

Script:

local modules = {}
modules.__index = modules

function modules:SearchModules(behavior: string, names: {string}, ancestor: Instance?): {ModuleScript}
	assert(ancestor:IsA("Instance"))
	local modulesMT = {}
	local children = ancestor:GetChildren()
	if not children then error("Ancestor doesn't have children!") end
	for i, v in ipairs(children) do
		if v.Name == names[i] then
			table.insert(modulesMT, v)
			print("Value inserted")
			setmetatable(modulesMT, modules)
			print("setmetatable()", i)
			print(unpack(modulesMT), unpack(modules))
			if i >= #names then break end
		else
			if behavior == "strict" then
				error("Failed when loading modules at", i, v.Name)
			elseif behavior == "nonstrict" then
				warn("Failed when loading modules at", i, v.Name)
				return nil
			else
				return nil
			end
		end
	end
	game:GetService("TestService"):Check(true, "modulesMT is going to be returned", script, 22)
	print(unpack(modulesMT))
	return modulesMT
end

local gottenModules = modules:SearchModules("strict", {"Utility", "Commands", "Debugger"}, script)
if gottenModules == nil then
	error("gottenModules: :SearchModules returned nil")
end

print(unpack(modules))
print(table.unpack(gottenModules)) -- Doesn't print anything, not even nil

Im really new to metatables so I don’t know how to make it work.

Debug attempts:

-I tried inserting modules to the script but the table still empty.

-I tried deleting the modules but it doesnt error. It just pass like nothing.

-I wrote a lot of prints and warns but most of them just don’t print anything

Also every error() don’t error.

Is my entire code wrong? How do I do this?
Any help is appreciated.

1 Like