首页 > 解决方案 > 如何覆盖 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)       -- 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)例如,当我使用 line 时,我的目标是__tostring打印出数据。目前,我的__tostring不起作用,但我很确定我正在尝试以错误的方式执行此操作。

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

标签: luatostring

解决方案


__tostring条目必须存在于您从中返回的每个实例的元表中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不仅如其名称所暗示的那样,而且还返回第一个函数参数。

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


推荐阅读