如何在 Lua 类中覆盖元表的 __tostring?

我有这个类:

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)       -- 需要先获取值,再放入表中
  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[面数: "..self.numSides..", 当前值: "..self.currentSide.."]"
  end

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

return Die

我的目标是当我使用 print(dieOne) 这行代码时,能够输出数据。目前,我的 __tostring 并不起作用,但是我很确定我是在错误的路径上。

如何实现我的目标?谢谢!

点赞
用户9593596
用户9593596

Die.new 返回的每个实例的元表中必须存在 __tostring。目前,你只是将其存储为普通条目。以下是确保它正确保存在每个关联元表中的方法:

function Die.new(side)
  -- 以前的代码...

  -- 设置元表
  local mt = {
    __tostring = __tostring
  }

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

在这里,我们利用了 setmetatable 不仅可以完成其名称所示的功能,还可以返回第一个函数参数的事实。

请注意,并不需要将函数本身命名为 __tostring。只有元表键必须是 "__tostring"

2019-07-29 16:29:14