Search code examples
performanceluaqueuepriority-queue

Efficiently storing and iterating over Lua multi-level queue


This is the add format:

AddToQueue( String identifier, function callfunc, int priority )

priority is guaranteed to be 0 to 4, with 0 being the highest priority. My current setup is this:

local tQueue = {
    [0] = {},
    [1] = {},
    [2] = {},
    [3] = {},
    [4] = {}
}

function AddToQueue( sName, funcCallback, iPriority )
    queue[iPriority or 0][sName] = funcCallback
end

function CallQueue()
    for i = 0, 4 do
        for _, func in pairs( queue[i] ) do
            local retval = func()

            if ( retval ~= nil ) then
                return retval
            end
        end
    end
end

This works, but I want to know if there's a better way to store and iterate the functions to prevent doing 5 pair loops every call. Thanks!


Solution

  • If you iterate your queue frequently, and new callbacks additions is infrequent, then you can just store everything in single table, sorting it each time you've added new callback.