如何覆盖 Lua class 中元表的 __tostring?

How can I override to __tostring of a metatable in a Lua class?

我有这个 class:

math.randomseed(os.time())
local Die = {}

function Die.new(side)
  if side ~= 4 or side ~= 6 or side ~= 8 or side ~= 10 or side ~= 12 or side ~= 10 or side ~= 100 then
    side = 6
  end
  ran = math.random(side)       -- had to get the value before placing in table
  local self = { numSides = side, currentSide = ran}

  local getValue = function(self)
    return self.currentSide
  end

  local roll = function(self)
    self.currentSide = math.random(self.numSides)
  end

  local __tostring = function(self) 
    return "Die[sides: "..self.numSides..", current value: "..self.currentSide.."]" 
  end

  return {
    numSides = self.numSides,
    currentSide = self.currentSide,
    getValue = getValue,
    roll = roll,
    __tostring = __tostring
  }
end

return Die

我的目标是当我使用 print(dieOne) 行时,例如让 __tostring 打印出数据。目前,我的 __tostring 不起作用,但我很确定我正在尝试以错误的方式执行此操作。

我怎样才能做到这一点?谢谢!

__tostring 条目必须存在于您 return 来自 Die.new 的每个实例的元表中。目前,您仅将其存储为普通条目。以下是确保它正确保存在每个关联的元表中的方法:

function Die.new(side)
  -- as before...

  -- setup the metatable
  local mt = {
    __tostring = __tostring
  }

  return setmetatable({
    numSides = self.numSides,
    currentSide = self.currentSide,
    getValue = getValue,
    roll = roll,
  }, mt)
end

在这里,我们利用了这样一个事实,即 setmetatable 不仅如其名称所暗示的那样,而且 return 是第一个函数参数。

请注意,无需调用函数本身__tostring。只有元表键必须是 "__tostring".