lua - 如何覆盖 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
不起作用,但我很确定我正在尝试以错误的方式执行此操作。
我怎样才能做到这一点?谢谢!
解决方案
该__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"
.
推荐阅读
- javascript - 检查会话是否桥接到另一个会话
- python - 没有名为“gensim.sklearn_api”的模块如何解决
- sas - 为什么在运行逐步回归时在 SAS 中出现堆栈溢出错误
- ubuntu - Ejabberd:安装期间的故障转储
- c# - pinvoke:线程与共享内存缓冲区
- python - 在 seaborn 中创造人工传奇
- amazon-web-services - 在 AWS 负载平衡的侦听器选项卡上找不到密码列
- sql - 用于在 Web 开发中存储数据的文本文件与 SQL 数据库
- android - 如何将 NavigationDrawer 与 TabLayout 和几个 Fragment 链接?
- flutter - Youtube Private Streaming in app 并检查用户是否为付费视频付费。?