当通过事件触发 i.e :Connect() 调用函数时传递附加参数

我正在尝试通过面向对象编程使我的匿名函数更好地工作,并且存在一些困难,因为我依赖于某个特定的作用域。以下是新旧的代码建议:

旧代码 - 可行

for _,portal in pairs(script.Parent:GetChildren())do
    if portal:IsA("Script") then continue end
    portal.Touched:Connect(function(part)
        local HRP = part.Parent:FindFirstChild("HumanoidRootPart")
        if not HRP then return end
        local DestinationName = portal:FindFirstChildOfClass("Attachment").Name
        local Destination = script.Parent:FindFirstChild(DestinationName):FindFirstChild(portal.Name)
        HRP.CFrame = Destination.WorldCFrame
    end)
end

新代码 - 有错误显然

local function portalTouched(part,portal)
    local HRP = part.Parent:FindFirstChild("HumanoidRootPart")
    if not HRP then return end
    local DestinationName = portal:FindFirstChildOfClass("Attachment").Name
    local Destination = script.Parent:FindFirstChild(DestinationName):FindFirstChild(portal.Name)
    HRP.CFrame = Destination.WorldCFrame
end

for _,portal in pairs(script.Parent:GetChildren())do
    if portal:IsA("Script") then continue end
    portal.Touched:Connect(portalTouched(portal))
end

连接函数到事件的问题是你不能传递任何附加参数, 如何解决作用域问题?任何建议都将不胜感激!

点赞
用户12278401
用户12278401

你可以使用高阶函数,其中使用 portal 调用并返回一个可以使用封闭函数参数的函数:

local function portalTouched(portal)
    return function(part)
        -- 在这个函数中我们可以使用 portal
        local HRP = part.Parent:FindFirstChild("HumanoidRootPart")
        if not HRP then return end
        local DestinationName = portal:FindFirstChildOfClass("Attachment").Name
        local Destination = script.Parent:FindFirstChild(DestinationName):FindFirstChild(portal.Name)
        HRP.CFrame = Destination.WorldCFrame
    end
end

for _,portal in pairs(script.Parent:GetChildren())do
    if portal:IsA("Script") then continue end
    portal.Touched:Connect(portalTouched(portal))
end
2020-07-18 13:35:20