__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.

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


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

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

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)


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.


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.