Good Code
The good version uses a metatable to attach methods to a score object. The approval rule is still a named method with visible intent.
Lesson 04
Use metatables for clear domain behavior, not for surprising mutation or hidden lookup rules.
local Score = {}
Score.__index = Score
function Score.new(value)
return setmetatable({ value = value }, Score)
end
function Score:passes()
-- Method syntax keeps the approval rule explicit.
return self.value >= 4
endlocal score_meta = {
__add = function(left, right)
-- Addition mutates the left operand instead of returning a new score.
left.value = left.value + right.value
return left
end,
}The good version uses a metatable to attach methods to a score object. The approval rule is still a named method with visible intent.
The bad version overloads addition and mutates the left value. A reader expecting arithmetic gets hidden state changes.