Module:GameData: Difference between revisions

sortByOrderTable: Initial implementation
(Implement getNamespacedID, getLocalID)
(sortByOrderTable: Initial implementation)
Line 12: Line 12:
-- If the entity ID is within the cache for the given entity type, then return it.
-- If the entity ID is within the cache for the given entity type, then return it.
-- Otherwise, returns nil
-- Otherwise, returns nil
function getCache(entityType, ID)
local function getCache(entityType, ID)
if type(entityType) == 'string' and type(ID) == 'string' then
if type(entityType) == 'string' and type(ID) == 'string' then
local cacheCat = indexCache[entityType]
local cacheCat = indexCache[entityType]
Line 22: Line 22:


-- Sets the cache for entity ID within the given entity type to idx.
-- Sets the cache for entity ID within the given entity type to idx.
function setCache(entityType, ID, idx)
local function setCache(entityType, ID, idx)
if type(entityType) == 'string' and type(ID) == 'string' and type(idx) == 'number' and idx == math.floor(idx) then
if type(entityType) == 'string' and type(ID) == 'string' and type(idx) == 'number' and idx == math.floor(idx) then
if indexCache[entityType] == nil then
if indexCache[entityType] == nil then
Line 55: Line 55:
end
end
return namespace, localID
return namespace, localID
end
function p.getCategoryData(entityType)
return GameData[entityType]
end
end


Line 141: Line 137:
end
end
return result
return result
end
-- Sorts the given dataTable by ID into the same order as orderTable
-- keepUnsorted specifies whether unsorted elements are included within the output. Default: true
--  unsorted elements will be at the end of the array, order is not guaranteed
-- idKey specifies the ID key to sort upon. Default: id
-- orderFunc specifies a custom order function if the default behaviour is not desired
function p.sortByOrderTable(dataTable, orderTable, keepUnsorted, idKey, orderFunc)
    -- Create index table from orderTable
    local orderIdx = {}
    for idx, v in ipairs(orderTable) do
        orderIdx[v] = idx
    end
    -- Determine if user-specified or default paramater values are to be used
    if type(keepUnsorted) ~= 'boolean' then
        keepUnsorted = true
    end
    if type(idKey) ~= 'string' then
        idKey = 'id'
    end
    if type(orderFunc) ~= 'function' then
        orderFunc = function(k1, k2)
            return orderIdx[k1[idKey]] < orderIdx[k2[idKey]]
        end
    end
    -- Build unsorted result table, removing unsorted elements if requested
    local resultTable = {}
    local resultItemCount = 0
    for idx, v in ipairs(dataTable) do
        local keyVal = v[idKey]
        if keyVal ~= nil then
            if keepUnsorted or orderIdx[keyVal] ~= nil then
                resultItemCount = resultItemCount + 1
                resultTable[resultItemCount] = v
            end
        end
    end
    -- Sort table
    table.sort(resultTable, orderFunc)
    return resultTable
end
end


return p
return p