如何在Lua类中重载元表的__tostring方法?

3

我有一个这样的类:

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 函数不能正常工作,但我相信我尝试的方法是错误的。
请问如何实现我的目标呢?感谢!
1个回答

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

< /p >
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"即可。

嘿,再次见面哈哈,mt是在新函数内部还是外部? - GreenSaber
它在函数 Die.new 内部。 - lubgr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接