__index inside metatable function problem

I have a function in a metatable and im trying to pass a numberval into it so it prints a number between 1 and the value given.
i dont know how to do it im pretty new. and if theres any way to make this work without the function inside the metatable please tell me.
script:

local randomnumtable = {
	__index = function(val,val1)
		math.random(1,val1)
	end
}
randomnumtable._index = randomnumtable
val = val or 0
function randomnumtable:newnumber()
	local self = setmetatable({},randomnumtable)
	print(self.val1 == 100)
end

randomnumtable:newnumber()

Not sure what you’re trying to do with your code, so I’ll show how I would do it.

local mt = setmetatable({}, {
    __index = function(self, key)
        if type(key) ~= "number" then -- only work for numbers
            return rawget(self, key) -- prevent infinite __index chain
        end

        return math.random(key) -- no lower limit, 1 is assumed
    end,
})

Whenever you index a table with a key, it will return a random number between 1 and the key, given that key is numerical. Unlike yours, this will only apply if the key is a number (preventing errors otherwise)

Example:

print(mt[4]) --> prints a random number from 1 to 4

However, I’d recommend not using metatables for this. It’s unnecessary to use metatables in this case when you can more easily just generate a random number normally. There’s no reason to make your code more complicated than it should be.

2 Likes

By the way what does rawget do, is there like a dev hub link?

The rawget function gets the value stored to the given index in the given table without firing the __index metamethod of that table’s metatable.

2 Likes