10:55:32.109 - Workspace.Script:4: attempt to index nil with number

Hello there.

I have made a function inside a metatable to fire upon being indexed.

It keeps erroring i dont know why.

I have a pcall function aswell so it doesnt error and it still does.

Please help.

ModuleScript:

local module = {}



local mt = setmetatable({}, {
	__index = function(self, key)
		if type(key) ~= "number" then
			return rawget(self, key) 
		end
		local success, response = pcall(
			"key" 
		)
		if success then
	    print(response)
			return math.random(key)
			end
	end,
})

return module
1 Like

What exactly is the script that requires the module doing?

Requires it then makes a key for it

local module = require(workspace.Module)

while wait(1) do
    print(module.mt[5])	
end

I see that you never actually add mt to the module. This is where your error is.

Do i use module. to add it?

module.mt

The variable mt in the module is on a local scope, which means it does not carry on to the module. Index using module.

pcall was not absolutely needed here, since no unpredictable instances of API usage was seen in this example of code. This clearly proves why that pcall was not needed.

1 Like
local mt = setmetatable({}, {

to

module.mt = setmetatable({}, {
1 Like