Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why this would cause stack overflows? [SOLVED]

The title explains it all. Here is the code I got from this:

local t = setmetatable({}, {
	__index = function(self, i)
		self[i] = i * 10 -- just as an example
		return self[i]
	end,
	__newindex = function(self, i, v)
		--don't do anything because we don't want you to set values to the table the normal way
	end
})
print(t[1]) -- Causes a C-Stack overflow

Thanks for reading :D

Edit: Ok so I guess I figure it out: So when you do print(t[1]), __index will be fired and run the function inside it(because t[1] is nil). In the function, we got self[i] = i * 10 to set the value, but because of __newindex, it prevent self[i] to be set the value, so self[i] would be nil. In the next line, return self[i] would fire __index again cus the self[i] is nil, it keep repeating until it cause a C-Stack overflow.

The solution is using rawset() to prevent __newindex to be fire.

1 answer

You set __index to return only when the Index exists, so if it not exists, it will cause a C-Stack overflow (because the __index can't return). So, to fix, just check if the Index exists in the table,, if not, then return nil, and everything will be working normally.

This discussion is preserved as it was. New answers, comments, and votes are closed.