我有一个这样的类:
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
函数不能正常工作,但我相信我尝试的方法是错误的。请问如何实现我的目标呢?感谢!
mt
是在新函数内部还是外部? - GreenSaberDie.new
内部。 - lubgr