请求有关对象/类的解释

问题描述 投票:0回答:1

我创建了一个脚本来生成迷宫,它按预期工作,但在编码过程中,我发现我应该以不同的方式创建对象实例,所以我重构了它:

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

lua roblox luau
1个回答
0
投票
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 类。使用实例设置实例字段。

© www.soinside.com 2019 - 2024. All rights reserved.