Understanding setmetatable

So been trying my hand at some OOP recently and seemed to be having it running quite smoothly for one project, today I began writing another script and pasted the ‘setmetatable’ line and it doesn’t work. Here’s my code, it works in one script but then in a test script it doesn’t.

local test = {}

local static = {
	["testValue"] = true,
}

function test.new(testNumber)
	local newTest = setmetatable({["testNumber"] = testNumber},{__index = static})
	print(newTest)
	return newTest
end

return test

so in this script, testvalue cannot be found in the returned table.

2 Likes

That code should work, and I just tested my own version of it and it worked.

Do you have any other scripts that modify the metatable of newTest?

2 Likes

nope, so just tried this on a new place with only this module script and another script to call it in the ServerScriptService which has this:

local test = require(game.ReplicatedStorage.test)
local newtest = test.new(1)
print(newtest)

again, “testValue” cant be found in the prints

2 Likes

Ohhhh, sorry i misunderstood your post.

The reason for that is what it seems - it’s not in the table. Metatables don’t add to the table; they don’t give inheritance. The __index metamethod can recreate this behaviour, though. The way it works is, Lua searches the main table. If the key is not found within that table, __index directs it to the metatable, or if __index is a function, it will run that. It then returns the search value from the metatable or the return value from the function to whatever requested it.

I hope that makes sense! If you have any more questions, please ask.

OOP in Lua ‘mocks’ typical Object-Oriented Programming; it can produce the same effect but does not use the same methods to do so.

1 Like

ahh okay thanks, that actually helps clear up a lot of issues. thanks!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.