From e95be75194cf98566f66788d5ed9aae15f38b474 Mon Sep 17 00:00:00 2001 From: speedwaystar Date: Fri, 13 Jan 2023 19:12:46 +0800 Subject: [PATCH] updated enumeration utility functions Signed-off-by: speedwaystar --- SmartBuff.globals.lua | 63 ++++++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 27 deletions(-) diff --git a/SmartBuff.globals.lua b/SmartBuff.globals.lua index c5d3ef2..df030da 100644 --- a/SmartBuff.globals.lua +++ b/SmartBuff.globals.lua @@ -53,39 +53,49 @@ NumberFontNormalHuge ---------------------------------------------------------------------------- --- Creates a table `t` indexed by both sequentially numbered `keys` _and_ `values`, --- thus supporting reverse lookup. Assumes numeric 'keys' and alphanumeric 'valuee'. --- ## Example --- ```lua --- t = enum( "foo", "bar" ); --- print(t.hello) -- prints the integer 1 --- print(t[1]) -- prints the string "foo" --- ``` ----@param t table +-- Returns an unumerated table. +---## Example +---``` +---Enum.Animals = Enum.MakeEnum ( "Dog", "Cat", "Rabbit" ) +---print( Enum.Animals.Cat ) -- prints "Cat" +---``` +---@param ... ... ---@return table -function enum(t) - for i = 1, #t do - local v = t[i] - --t[i] = nil - t[v] = i +function Enum.MakeEnum(...) + return tInvert({...}) + -- for i = 1, #t do + -- local v = t[i] + -- --t[i] = nil + -- t[v] = i + -- end + -- return t end - return t + +-- Returns an unumerated table from an existing table. +---## Example +---``` +---Fish = { "Loach", "Pike", "Herring" } +---Enum.Fish = Enum.MakeEnumFromTable(Fish) +---print(Enum.Fish.Herring) -- prints "Herring" +---``` +function Enum.MakeEnumFromTable(t) + return tInvert(t) end --- Creates a table `t` of self-indexed values +-- Returns a table `t` of self-indexed values -- ## Example -- ```lua -- t = dict( "foo", "bar") -- print(t.foo) -- prints the string "foo" -- ``` ----@param list table +---@param tbl table ---@return table -function dict(list) - for k, v in pairs(list) do - list[k] = nil - list[v] = v +function Enum.MakeDict(tbl) + local t = {}; + for k, v in ipairs(tbl) do + t[v] = v; end - return list + return t; end -- Returns a copy of `list` with `keys` and `values` inverted @@ -96,12 +106,11 @@ end ---print(t.foo); -- prints the number 1 ---print(s[1]); -- prints the string "foo"; ---``` ----@generic T ----@param list T[] ----@return T out -function table.invert(list) +---@param tbl table +---@return table out +function table.invert(tbl) local out = {} - for k, v in pairs(list) do + for k, v in pairs(tbl) do out[v] = k end return out