From 792738c5cc1ce520ce54da09c44f61aff5d431de Mon Sep 17 00:00:00 2001 From: Kazhnuz Date: Sat, 15 May 2021 15:50:15 +0200 Subject: [PATCH] feat: add table parsing --- sonic-radiance.love/birb/utils/table.lua | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/sonic-radiance.love/birb/utils/table.lua b/sonic-radiance.love/birb/utils/table.lua index e76fb92..ddf1441 100644 --- a/sonic-radiance.love/birb/utils/table.lua +++ b/sonic-radiance.love/birb/utils/table.lua @@ -77,4 +77,27 @@ function Table.average(table) return Table.sum(table) / #table end +--Parse a basic list into a structured table. Return an error if the number of arguments is not the same +---@param table table the list to parse into a table +---@param structure table the structure to create the table : each name correspond to an attribute of the parsed table +---@param nullableNbr integer the number of nullable argument (at the end of the functions) (can be null) +---@return table parsedTable the parsed table +function Table.parse(table, structure, nullableNbr) + local parsedTable = {} + assert(table ~= nil, "The table to parse can't be null") + assert(structure ~= nil, "The table structure can't be null") + nullableNbr = nullableNbr or 0 + + if ((#table) > (#structure)) or ((#table) < (#structure - nullableNbr)) then + error("The table to parse doesn't have the right number of arguments: " .. #table .. " instead of " .. #structure .. " and " .. nullableNbr .. " nullables") + else + for i, key in ipairs(structure) do + --print(i, key, table[i]) + parsedTable[key] = table[i] + end + end + + return parsedTable +end + return Table