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

标签 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) 行时,例如,让 __tostring 打印出数据。目前,我的 __tostring 不起作用,但我很确定我正在尝试以错误的方式执行此操作。

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

最佳答案

__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"

关于lua - 如何覆盖 Lua 类中元表的 __tostring?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257794/

相关文章:

android - 方法调用 'toString' 可能会产生 'java.lang.NullPointerException' ?

lua - 魔兽世界 (Lua) 与 Adafruit Gemma 的交流

javascript - 使用 tostring 和 number 方法的数字总和 javascript

linux - Liblua5.3-lpeg.so.2 : cannot open shared object file

regex - 在 Lua 5.1 中将可重复字符串匹配为 "whole word"

java - toString 使用 StringBuilder 覆盖具有特定选项卡的格式

java - 在 Java 枚举中覆盖 valueof() 和 toString()

java - 语法错误,在java中插入 "EnumBody"和 "enum Identifier"

lua - 在 Lua Torch 中,两个零矩阵的乘积有 nan 项

c++ - 是否需要使用共享库的不同 lua_State?