Refer to object property in that same object?

Hey! I’m trying to make the following work:

local module = {
	pit = game.Workspace:WaitForChild("Pit"),
	pits = {
		gates = module.pit.Gates	
	}
}

return module

The idea is that I can work further on the “pit” variable, so I can later do this:

-- Normal script
local pitModule = require(game.ServerScriptService.pitModule)
pitmodule.pit.Name == "Some other name"
pits.gates.pit5.Open.Value = true

Ideally I’d even love to change pit to pits, so if I say “pitModule.pits”, I get the upper variable, if I put a dot and something else behind it, it just goes into the object and searches, like how I did below.

Thanks in advance!

Kr
Jonas

Do you mean that you’d like a table to give you the ‘game.WOrkspace:WaitForChild(“Pit”)’ object when you reference the module as module.pits, but when you reference the table as module.pits.pit5 it will give you the pit5 object from the gates object?

Ideally yes. But if I can get it working like in my script above that would already be awesome.

You can do this with metamethods. Highly recommend you read this and this to learn more

Module:

local refs = {
	pitObj = game.Workspace:WaitForChild 'Pit';
	gates  = {
		pit1 = game.Workspace.pit1;
		pit2 = {ClassName = "I am a table"};
	};
}

local module = { }
setmetatable(module, {
	__index = function (t, k)
		return setmetatable({ }, {
			__index = function (_, i)
				if refs[i] then
					return refs[i]
				else
					return refs.pitObj[i]
				end
			end
		})
	end
})

return module

Use in another script:


local pitModule = require(script.PitsModule)

print("Pit object:", pitModule.pits.Name);
print("Gates table ref:", pitModule.pits.gates);
print("Pit1 name:", pitModule.pits.gates.pit1.Name);
print("Pit2 table class:", pitModule.pits.gates.pit2.ClassName);