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