如何使我的事件在条件为真时仅触发一次而不是每次更新迭代都触发?

我的事件监听器代码如下:

local events = {}

function registerEvent (event)
    table.insert(events, event)
end

function unregisterEvent (event)
    table.remove(events, event)
end

function processEvents ()
    for _, event in pairs(events) do
        for _, condition in pairs(event.conditions) do
            if condition() then
                event.triggered = true;
            else
                event.triggered = false;
                break
            end
        end

        if event.triggered then
            event.callback()
        end
    end
end

registerEvent
{
    conditions = {
        function () return Keyboard.Shift == true end
    },
    callback = function () text = "已触发" end
}

registerEvent
{
    conditions = {
        function () return Keyboard.Shift == false end
    },
    callback = function () text = "未触发" end
}

更新循环代码简单地是:

function OnUpdate(deltaTime)
    processEvents()
end

基本上我想要的是当条件为真时回调只触发一次,而不是每次更新都触发(然后在条件不为真时重置触发检查)。

点赞
用户63791
用户63791

根据评论中的讨论,您可以通过以下修改processEvents来使其按照您想要的方式工作:

function processEvents ()
    for _, event in pairs(events) do
        for _, condition in pairs(event.conditions) do
            if condition() then
                event.triggered = true;
            else
                event.triggered = false
                event.triggeredbefore = false
                break
            end
        end

        if event.triggered and not event.triggeredbefore then
            event.callback()
            event.triggeredbefore = true
        end
    end
end
2016-06-24 00:47:57