Advertisement
Guest User

lua/includes/extensions/table.lua

a guest
Nov 1st, 2014
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 16.10 KB | None | 0 0
  1. --[[---------------------------------------------------------
  2.    Name: Inherit( t, base )
  3.    Desc: Copies any missing data from base to t
  4. -----------------------------------------------------------]]
  5. function table.Inherit( t, base )
  6.  
  7.     for k, v in pairs( base ) do
  8.         if ( t[k] == nil ) then t[k] = v end
  9.     end
  10.    
  11.     t["BaseClass"] = base
  12.    
  13.     return t
  14.  
  15. end
  16.  
  17.  
  18. --[[---------------------------------------------------------
  19.     Name: Copy(t, lookup_table)
  20.     Desc: Taken straight from http://lua-users.org/wiki/PitLibTablestuff
  21.           and modified to the new Lua 5.1 code by me.
  22.           Original function by PeterPrade!
  23. -----------------------------------------------------------]]
  24. function table.Copy(t, lookup_table)
  25.     if (t == nil) then return nil end
  26.    
  27.     local copy = {}
  28.     setmetatable(copy, debug.getmetatable(t))
  29.     for i,v in pairs(t) do
  30.         if ( !istable(v) ) then
  31.             copy[i] = v
  32.         else
  33.             lookup_table = lookup_table or {}
  34.             lookup_table[t] = copy
  35.             if lookup_table[v] then
  36.                 copy[i] = lookup_table[v] -- we already copied this table. reuse the copy.
  37.             else
  38.                 copy[i] = table.Copy(v,lookup_table) -- not yet copied. copy it.
  39.             end
  40.         end
  41.     end
  42.     return copy
  43. end
  44.  
  45. --[[---------------------------------------------------------
  46.     Name: Empty( tab )
  47.     Desc: Empty a table
  48. -----------------------------------------------------------]]
  49. function table.Empty( tab )
  50.  
  51.     for k, v in pairs( tab ) do
  52.         tab[k] = nil
  53.     end
  54.  
  55. end
  56.  
  57. --[[---------------------------------------------------------
  58.     Name: CopyFromTo( FROM, TO )
  59.     Desc: Make TO exactly the same as FROM - but still the same table.
  60. -----------------------------------------------------------]]
  61. function table.CopyFromTo( FROM, TO )
  62.  
  63.     -- Erase values from table TO
  64.     table.Empty( TO )
  65.    
  66.     -- Copy values over
  67.     table.Merge( TO, FROM )
  68.    
  69. end
  70.  
  71.  
  72. --[[---------------------------------------------------------
  73.    Name: xx
  74.    Desc: xx
  75. -----------------------------------------------------------]]
  76. function table.Merge(dest, source)
  77.  
  78.     for k,v in pairs(source) do
  79.    
  80.         if ( type(v) == 'table' && type(dest[k]) == 'table' ) then
  81.             -- don't overwrite one table with another;
  82.             -- instead merge them recurisvely
  83.             table.Merge(dest[k], v)
  84.         else
  85.             dest[k] = v
  86.         end
  87.     end
  88.    
  89.     return dest
  90.    
  91. end
  92.  
  93.  
  94. --[[---------------------------------------------------------
  95.    Name: xx
  96.    Desc: xx
  97. -----------------------------------------------------------]]
  98. function table.HasValue( t, val )
  99.     for k,v in pairs(t) do
  100.         if (v == val ) then return true end
  101.     end
  102.     return false
  103. end
  104.  
  105. table.InTable = HasValue
  106.  
  107.  
  108. --[[---------------------------------------------------------
  109.    Name: table.Add( dest, source )
  110.    Desc: Unlike merge this adds the two tables together and discards keys.
  111. -----------------------------------------------------------]]
  112. function table.Add( dest, source )
  113.  
  114.     -- At least one of them needs to be a table or this whole thing will fall on its ass
  115.     if (type(source)!='table') then return dest end
  116.    
  117.     if (type(dest)!='table') then dest = {} end
  118.  
  119.     for k,v in pairs(source) do
  120.         table.insert( dest, v )
  121.     end
  122.    
  123.     return dest
  124. end
  125.  
  126. --[[---------------------------------------------------------
  127.    Name: table.SortDesc( table )
  128.    Desc: Like Lua's default sort, but descending
  129. -----------------------------------------------------------]]
  130. function table.SortDesc( Table )
  131.  
  132.     return table.sort( Table, function(a, b) return a > b end )
  133. end
  134.  
  135. --[[---------------------------------------------------------
  136.    Name: table.SortByKey( table )
  137.    Desc: Returns a table sorted numerically by Key value
  138. -----------------------------------------------------------]]
  139.  
  140. function table.SortByKey( Table, Desc )
  141.  
  142.     local temp = {}
  143.  
  144.     for key, _ in pairs(Table) do table.insert(temp, key) end
  145.     if ( Desc ) then
  146.         table.sort(temp, function(a, b) return Table[a] < Table[b] end)
  147.     else
  148.         table.sort(temp, function(a, b) return Table[a] > Table[b] end)
  149.     end
  150.  
  151.     return temp
  152. end
  153.  
  154. --[[---------------------------------------------------------
  155.    Name: table.Count( table )
  156.    Desc: Returns the number of keys in a table
  157. -----------------------------------------------------------]]
  158.  
  159. function table.Count (t)
  160.   local i = 0
  161.   for k in pairs(t) do i = i + 1 end
  162.   return i
  163. end
  164.  
  165.  
  166. --[[---------------------------------------------------------
  167.    Name: table.Random( table )
  168.    Desc: Return a random key
  169. -----------------------------------------------------------]]
  170.  
  171. function table.Random (t)
  172.  
  173.   local rk = math.random( 1, table.Count( t ) )
  174.   local i = 1
  175.   for k, v in pairs(t) do
  176.     if ( i == rk ) then return v, k end
  177.     i = i + 1
  178.   end
  179.  
  180. end
  181.  
  182.  
  183. --[[----------------------------------------------------------------------
  184.    Name: table.IsSequential( table )
  185.    Desc: Returns true if the tables
  186.      keys are sequential
  187. -------------------------------------------------------------------------]]
  188.  
  189. function table.IsSequential(t)
  190.     local i = 1
  191.     for key, value in pairs (t) do
  192.         if not tonumber(i) or key ~= i then return false end
  193.         i = i + 1
  194.     end
  195.     return true
  196. end
  197.  
  198.  
  199. --[[---------------------------------------------------------
  200.    Name: table.ToString( table,name,nice )
  201.    Desc: Convert a simple table to a string
  202.         table = the table you want to convert (table)
  203.         name  = the name of the table (string)
  204.         nice  = whether to add line breaks and indents (bool)
  205. -----------------------------------------------------------]]
  206.  
  207. function table.ToString(t,n,nice)
  208.     local       nl,tab  = "",  ""
  209.     if nice then    nl,tab = "\n", "\t" end
  210.  
  211.     local function MakeTable ( t, nice, indent, done)
  212.         local str = ""
  213.         local done = done or {}
  214.         local indent = indent or 0
  215.         local idt = ""
  216.         if nice then idt = string.rep ("\t", indent) end
  217.  
  218.         local sequential = table.IsSequential(t)
  219.  
  220.         for key, value in pairs (t) do
  221.  
  222.             str = str .. idt .. tab .. tab
  223.  
  224.             if not sequential then
  225.                 if type(key) == "number" or type(key) == "boolean" then
  226.                     key ='['..tostring(key)..']' ..tab..'='
  227.                 else
  228.                     key = tostring(key) ..tab..'='
  229.                 end
  230.             else
  231.                 key = ""
  232.             end
  233.  
  234.             if istable(value) and not done [value] then
  235.  
  236.                 done [value] = true
  237.                 str = str .. key .. tab .. '{' .. nl
  238.                 .. MakeTable (value, nice, indent + 1, done)
  239.                 str = str .. idt .. tab .. tab ..tab .. tab .."},".. nl
  240.  
  241.             else
  242.                
  243.                 if  type(value) == "string" then
  244.                     value = '"'..tostring(value)..'"'
  245.                 elseif  type(value) == "Vector" then
  246.                     value = 'Vector('..value.x..','..value.y..','..value.z..')'
  247.                 elseif  type(value) == "Angle" then
  248.                     value = 'Angle('..value.pitch..','..value.yaw..','..value.roll..')'
  249.                 else
  250.                     value = tostring(value)
  251.                 end
  252.                
  253.                 str = str .. key .. tab .. value .. ",".. nl
  254.  
  255.             end
  256.  
  257.         end
  258.         return str
  259.     end
  260.     local str = ""
  261.     if n then str = n.. tab .."=" .. tab end
  262.     str = str .."{" .. nl .. MakeTable ( t, nice) .. "}"
  263.     return str
  264. end
  265.  
  266. --[[---------------------------------------------------------
  267.    Name: table.Sanitise( table )
  268.    Desc: Converts a table containing vectors, angles, bools so it can be converted to and from keyvalues
  269. -----------------------------------------------------------]]
  270. function table.Sanitise( t, done )
  271.  
  272.     local done = done or {}
  273.     local tbl = {}
  274.  
  275.     for k, v in pairs ( t ) do
  276.    
  277.         if ( istable( v ) and !done[ v ] ) then
  278.  
  279.             done[ v ] = true
  280.             tbl[ k ] = table.Sanitise ( v, done )
  281.  
  282.         else
  283.  
  284.             if ( type(v) == "Vector" ) then
  285.  
  286.                 local x, y, z = v.x, v.y, v.z
  287.                 if y == 0 then y = nil end
  288.                 if z == 0 then z = nil end
  289.                 tbl[k] = { __type = "Vector", x = x, y = y, z = z }
  290.  
  291.             elseif ( type(v) == "Angle" ) then
  292.  
  293.                 local p,y,r = v.pitch, v.yaw, v.roll
  294.                 if p == 0 then p = nil end
  295.                 if y == 0 then y = nil end
  296.                 if r == 0 then r = nil end
  297.                 tbl[k] = { __type = "Angle", p = p, y = y, r = r }
  298.  
  299.             elseif ( type(v) == "boolean" ) then
  300.            
  301.                 tbl[k] = { __type = "Bool", tostring( v ) }
  302.  
  303.             else
  304.            
  305.                 tbl[k] = tostring(v)
  306.  
  307.             end
  308.            
  309.            
  310.         end
  311.        
  312.        
  313.     end
  314.    
  315.     return tbl
  316.    
  317. end
  318.  
  319.  
  320. --[[---------------------------------------------------------
  321.    Name: table.DeSanitise( table )
  322.    Desc: Converts a Sanitised table back
  323. -----------------------------------------------------------]]
  324. function table.DeSanitise( t, done )
  325.  
  326.     local done = done or {}
  327.     local tbl = {}
  328.  
  329.     for k, v in pairs ( t ) do
  330.    
  331.         if ( istable( v ) and !done[ v ] ) then
  332.        
  333.             done[ v ] = true
  334.  
  335.             if ( v.__type ) then
  336.            
  337.                 if ( v.__type == "Vector" ) then
  338.                
  339.                     tbl[ k ] = Vector( v.x, v.y, v.z )
  340.                
  341.                 elseif ( v.__type == "Angle" ) then
  342.                
  343.                     tbl[ k ] = Angle( v.p, v.y, v.r )
  344.                    
  345.                 elseif ( v.__type == "Bool" ) then
  346.                    
  347.                     tbl[ k ] = ( v[1] == "true" )
  348.                    
  349.                 end
  350.            
  351.             else
  352.            
  353.                 tbl[ k ] = table.DeSanitise( v, done )
  354.                
  355.             end
  356.            
  357.         else
  358.        
  359.             tbl[ k ] = v
  360.            
  361.         end
  362.        
  363.     end
  364.    
  365.     return tbl
  366.    
  367. end
  368.  
  369. function table.ForceInsert( t, v )
  370.  
  371.     if ( t == nil ) then t = {} end
  372.    
  373.     table.insert( t, v )
  374.    
  375.     return t
  376.    
  377. end
  378.  
  379.  
  380. --[[---------------------------------------------------------
  381.    Name: table.SortByMember( table )
  382.    Desc: Sorts table by named member
  383. -----------------------------------------------------------]]
  384. function table.SortByMember( Table, MemberName, bAsc )
  385.  
  386.     local TableMemberSort = function( a, b, MemberName, bReverse )
  387.    
  388.         --
  389.         -- All this error checking kind of sucks, but really is needed
  390.         --
  391.         if ( !istable(a) ) then return !bReverse end
  392.         if ( !istable(b) ) then return bReverse end
  393.         if ( !a[MemberName] ) then return !bReverse end
  394.         if ( !b[MemberName] ) then return bReverse end
  395.  
  396.         if ( type( a[MemberName] ) == "string" ) then
  397.  
  398.             if ( bReverse ) then
  399.                 return a[MemberName]:lower() < b[MemberName]:lower()
  400.             else
  401.                 return a[MemberName]:lower() > b[MemberName]:lower()
  402.             end
  403.  
  404.         end
  405.    
  406.         if ( bReverse ) then
  407.             return a[MemberName] < b[MemberName]
  408.         else
  409.             return a[MemberName] > b[MemberName]
  410.         end
  411.        
  412.     end
  413.  
  414.     table.sort( Table, function(a, b) return TableMemberSort( a, b, MemberName, bAsc or false ) end )
  415.    
  416. end
  417.  
  418.  
  419. --[[---------------------------------------------------------
  420.    Name: table.LowerKeyNames( table )
  421.    Desc: Lowercase the keynames of all tables
  422. -----------------------------------------------------------]]
  423. function table.LowerKeyNames( Table )
  424.  
  425.     local OutTable = {}
  426.  
  427.     for k, v in pairs( Table ) do
  428.    
  429.         -- Recurse
  430.         if ( istable( v ) ) then
  431.             v = table.LowerKeyNames( v )
  432.         end
  433.        
  434.         OutTable[ k ] = v
  435.        
  436.         if ( isstring( k ) ) then
  437.    
  438.             OutTable[ k ]  = nil
  439.             OutTable[ string.lower( k ) ] = v
  440.        
  441.         end    
  442.    
  443.     end
  444.    
  445.     return OutTable
  446.    
  447. end
  448.  
  449.  
  450. --[[---------------------------------------------------------
  451.    Name: table.LowerKeyNames( table )
  452.    Desc: Lowercase the keynames of all tables
  453. -----------------------------------------------------------]]
  454. function table.CollapseKeyValue( Table )
  455.  
  456.     local OutTable = {}
  457.    
  458.     for k, v in pairs( Table ) do
  459.    
  460.         local Val = v.Value
  461.    
  462.         if ( istable( Val ) ) then
  463.             Val = table.CollapseKeyValue( Val )
  464.         end
  465.        
  466.         OutTable[ v.Key ] = Val
  467.    
  468.     end
  469.    
  470.     return OutTable
  471.  
  472. end
  473.  
  474. --[[---------------------------------------------------------
  475.    Name: table.ClearKeys( table, bSaveKey )
  476.    Desc: Clears the keys, converting to a numbered format
  477. -----------------------------------------------------------]]
  478. function table.ClearKeys( Table, bSaveKey )
  479.  
  480.     local OutTable = {}
  481.    
  482.     for k, v in pairs( Table ) do
  483.         if ( bSaveKey ) then
  484.             v.__key = k
  485.         end
  486.         table.insert( OutTable, v )
  487.     end
  488.    
  489.     return OutTable
  490.  
  491. end
  492.  
  493.  
  494.  
  495. local function fnPairsSorted( pTable, Index )
  496.  
  497.     if ( Index == nil ) then
  498.    
  499.         Index = 1
  500.    
  501.     else
  502.    
  503.         for k, v in pairs( pTable.__SortedIndex ) do
  504.             if ( v == Index ) then
  505.                 Index = k + 1
  506.                 break
  507.             end
  508.         end
  509.        
  510.     end
  511.    
  512.     local Key = pTable.__SortedIndex[ Index ]
  513.     if ( !Key ) then
  514.         pTable.__SortedIndex = nil
  515.         return
  516.     end
  517.    
  518.     Index = Index + 1
  519.    
  520.     return Key, pTable[ Key ]
  521.  
  522. end
  523.  
  524. --[[---------------------------------------------------------
  525.    A Pairs function
  526.  
  527.         Sorted by TABLE KEY
  528.        
  529. -----------------------------------------------------------]]
  530. function SortedPairs( pTable, Desc )
  531.  
  532.     pTable = table.Copy( pTable )
  533.    
  534.     local SortedIndex = {}
  535.     for k, v in pairs( pTable ) do
  536.         table.insert( SortedIndex, k )
  537.     end
  538.    
  539.     if ( Desc ) then
  540.         table.sort( SortedIndex, function(a,b) return a>b end )
  541.     else
  542.         table.sort( SortedIndex )
  543.     end
  544.     pTable.__SortedIndex = SortedIndex
  545.  
  546.     return fnPairsSorted, pTable, nil
  547.    
  548. end
  549.  
  550. --[[---------------------------------------------------------
  551.    A Pairs function
  552.  
  553.         Sorted by VALUE
  554.        
  555. -----------------------------------------------------------]]
  556. function SortedPairsByValue( pTable, Desc )
  557.  
  558.     pTable = table.ClearKeys( pTable )
  559.    
  560.     if ( Desc ) then
  561.         table.sort( pTable, function(a,b) return a>b end )
  562.     else
  563.         table.sort( pTable )
  564.     end
  565.  
  566.     return ipairs( pTable )
  567.    
  568. end
  569.  
  570. --[[---------------------------------------------------------
  571.    A Pairs function
  572.  
  573.         Sorted by Member Value (All table entries must be a table!)
  574.        
  575. -----------------------------------------------------------]]
  576. function SortedPairsByMemberValue( pTable, pValueName, Desc )
  577.  
  578.     Desc = Desc or false
  579.    
  580.     local pSortedTable = table.ClearKeys( pTable, true )
  581.    
  582.     table.SortByMember( pSortedTable, pValueName, !Desc )
  583.    
  584.     local SortedIndex = {}
  585.     for k, v in ipairs( pSortedTable ) do
  586.         table.insert( SortedIndex, v.__key )
  587.     end
  588.    
  589.     pTable.__SortedIndex = SortedIndex
  590.  
  591.     return fnPairsSorted, pTable, nil
  592.    
  593. end
  594.  
  595. --[[---------------------------------------------------------
  596.    A Pairs function    
  597. -----------------------------------------------------------]]
  598. function RandomPairs( pTable, Desc )
  599.  
  600.     local Count = table.Count( pTable )
  601.     pTable = table.Copy( pTable )
  602.    
  603.     local SortedIndex = {}
  604.     for k, v in pairs( pTable ) do
  605.         table.insert( SortedIndex, { key = k, val = math.random( 1, 1000 ) } )
  606.     end
  607.    
  608.     if ( Desc ) then
  609.         table.sort( SortedIndex, function(a,b) return a.val>b.val end )
  610.     else
  611.         table.sort( SortedIndex, function(a,b) return a.val<b.val end )
  612.     end
  613.    
  614.     for k, v in pairs( SortedIndex ) do
  615.         SortedIndex[ k ] = v.key;
  616.     end
  617.    
  618.     pTable.__SortedIndex = SortedIndex
  619.  
  620.     return fnPairsSorted, pTable, nil
  621.    
  622. end
  623.  
  624. --[[---------------------------------------------------------
  625.     GetFirstKey
  626. -----------------------------------------------------------]]
  627. function table.GetFirstKey( t )
  628.  
  629.     local k, v = next( t )
  630.     return k
  631.    
  632. end
  633.  
  634. function table.GetFirstValue( t )
  635.  
  636.     local k, v = next( t )
  637.     return v
  638.    
  639. end
  640.  
  641. function table.GetLastKey( t )
  642.  
  643.     local k, v = next( t, table.Count(t) - 1 )
  644.     return k
  645.    
  646. end
  647.  
  648. function table.GetLastValue( t )
  649.  
  650.     local k, v = next( t, table.Count(t) - 1 )
  651.     return v
  652.    
  653. end
  654.  
  655. function table.FindNext( tab, val )
  656.    
  657.     local bfound = false
  658.     for k, v in pairs( tab ) do
  659.         if ( bfound ) then return v end
  660.         if ( val == v ) then bfound = true end
  661.     end
  662.    
  663.     return table.GetFirstValue( tab )  
  664.    
  665. end
  666.  
  667. function table.FindPrev( tab, val )
  668.    
  669.     local last = table.GetLastValue( tab )
  670.     for k, v in pairs( tab ) do
  671.         if ( val == v ) then return last end
  672.         last = v
  673.     end
  674.    
  675.     return last
  676.    
  677. end
  678.  
  679. function table.GetWinningKey( tab )
  680.    
  681.     local highest = -10000
  682.     local winner = nil
  683.    
  684.     for k, v in pairs( tab ) do
  685.         if ( v > highest ) then
  686.             winner = k
  687.             highest = v
  688.         end
  689.     end
  690.    
  691.     return winner
  692.    
  693. end
  694.  
  695. function table.KeyFromValue( tbl, val )
  696.     for key, value in pairs( tbl ) do
  697.         if ( value == val ) then return key end
  698.     end
  699. end
  700.  
  701. function table.RemoveByValue( tbl, val )
  702.  
  703.     local key = table.KeyFromValue( tbl, val )
  704.     if ( !key ) then return false end
  705.    
  706.     table.remove( tbl, key )
  707.     return key;
  708.    
  709. end
  710.  
  711. function table.KeysFromValue( tbl, val )
  712.     local res = {}
  713.     for key, value in pairs( tbl ) do
  714.         if ( value == val ) then table.insert( res, key ) end
  715.     end
  716.     return res
  717. end
  718.  
  719. function table.Reverse( tbl )
  720.  
  721.      local len = #tbl;
  722.      local ret = {};
  723.      
  724.      for i = len, 1, -1 do
  725.           ret[len-i+1] = tbl[i];
  726.      end
  727.  
  728.      return ret;
  729.  
  730. end
  731.  
  732. function table.ForEach( tab, funcname )
  733.  
  734.     for k, v in pairs( tab ) do
  735.         funcname( k, v )
  736.     end
  737.  
  738. end
  739.  
  740. function table.GetKeys( tab )
  741.    
  742.     local keys = {}
  743.     local id = 1
  744.  
  745.     for k, v in pairs( tab ) do
  746.         keys[ id ] = k
  747.         id = id + 1
  748.     end
  749.    
  750.     return keys
  751.  
  752. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement