Lua

Lesson 04

Metatable operator boundaries

Use metatables for clear domain behavior, not for surprising mutation or hidden lookup rules.

Good Code

src/review_score.lua
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
end

Bad Code

review_score.lua
local 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,
}

Review Notes

What to review

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.

Bad Code

The bad version overloads addition and mutates the left value. A reader expecting arithmetic gets hidden state changes.

Takeaways

  • Metatable review should check whether metamethods keep domain operations visible or hide side effects.