gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:51:28 24 4
gpt4 key购买 nike

我有这门课:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com