我创建了一个脚本来生成迷宫,它按预期工作,但在编码过程中,我发现我应该以不同的方式创建对象实例,所以我重构了它:
local Cell = {
index = nil,
coordinates = Vector2.zero,
wasVisited = false,
markAsVisited = function (self)
self.wasVisited = true
end,
new = function(self, index: number, coordinates: Vector2)
local cell = table.clone(self)
cell.index = index
cell.coordinates = coordinates
return cell
end,
}
return Cell
到
local Cell = {
index = nil,
coordinates = Vector2.zero,
wasVisited = false
}
function Cell:new(index: number, coordinates: Vector2)
local instance = setmetatable({}, self)
self.__index = self
self.index = index
self.coordinates = coordinates
return instance
end
function Cell:markAsVisited()
self.wasVisited = true
end
return Cell
而不是
我明白了
有人可以向我解释一下为什么吗?
[编辑]
我暂时将存储库标记为公开:https://github.com/Alcadur/roblox-maze
Maze
文件位于 ServerScriptService/objects
function Cell:new(index: number, coordinates: Vector2)
local instance = setmetatable({}, self)
self.__index = self
self.index = index
self.coordinates = coordinates
return instance
end
您创建了一个新实例,但随后继续使用
self
,即 Cell 类。使用实例设置实例字段。