Advertisement
rockbandcheeseman

General Libraries

Aug 26th, 2013
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.59 KB | None | 0 0
  1. -- Table Library
  2.  
  3. --[[
  4.     Documentation
  5.    
  6.     This is my extention of the Lua tables library.  I hope you find them all useful.
  7.    
  8.     The following examples will all be interrelated and will create a very basic stats table.
  9.    
  10.     Here are descriptions of each function and how to use them:
  11.    
  12.     table.save(t, filename)
  13.    
  14.         -- t: <table> The table you'll be saving into a textfile.
  15.         -- filename: <string> The name of the file you'll be saving this table to.
  16.        
  17.         Example:
  18.        
  19.             function OnScriptUnload()
  20.            
  21.                 table.save(players, "players.data")
  22.             end
  23.            
  24.         Notes:
  25.        
  26.             -- By default, table.save saves your table in "Documents\\My Games\\Halo\\data".
  27.            
  28.     table.load(filename)
  29.    
  30.         -- filename: <string> The name of the file you want to load a table from.
  31.        
  32.         Example:
  33.        
  34.             function OnScriptLoad(process, game, persistent)
  35.            
  36.                 players = table.load("players.data")
  37.             end
  38.        
  39.             function OnPlayerJoin(player)
  40.            
  41.                 makestats(player)
  42.             end
  43.            
  44.             function makestats(player)
  45.            
  46.                 local hash = gethash(player)
  47.                 stats[hash] = table.load(hash .. ".data")
  48.                
  49.                 players[hash] = players[hash] or {}
  50.                 players[hash].joins = players[hash].joins or 0 + 1
  51.                
  52.                 stats[hash].name = stats[hash].name or getname(player)
  53.                
  54.                 stats[hash].kills = stats[hash].kills or {}
  55.                 stats[hash].kills.humanweap = stats[hash].kills.humanweap or 0
  56.                 stats[hash].kills.covenantweap = stats[hash].kills.covenantweap or 0
  57.             end
  58.        
  59.         Notes:
  60.        
  61.             -- If the file doesn't exist or is empty, table.load returns an empty table {}.
  62.            
  63.     table.len(t)
  64.    
  65.         -- t: <table> Table you want to find the length of.
  66.        
  67.         Returns:  Total length of table.
  68.        
  69.         Example:
  70.        
  71.             local total_players = table.len(players)
  72.            
  73.         Notes:
  74.        
  75.             -- The reason this function is necessary is because #t returns the length of a table as defined by ipairs.  This means Lua begins at index 1 of table t and adds 1 to the index until the value at the current index is nil.  If you have a table that is indexed by hashes, #players will return 0 because players[1] = nil.  table.len returns the length of a table including non-numeric keys.
  76.            
  77.     table.find(t, v, [case])
  78.    
  79.         -- t: <table> Table you're searching.
  80.         -- v: <any type> Value you're searching for in the table.
  81.         -- case: <boolean> Defines if the value should be case-sensitive (default = true).
  82.        
  83.         Returns:  The key at which the specified value is found.
  84.        
  85.         Example:
  86.        
  87.             swears = {"balls", "boners", "poppycock"}  -- My name is Nuggets and I (dis)approve of these words.
  88.            
  89.             function OnServerChat(player, type, message)
  90.            
  91.                 if player then
  92.                     local words = tokenizestring(message)
  93.                     for k,v in ipairs(words) do
  94.                         if table.find(swears, v, false) then  -- ensures that "boners" as well as "BONERS" and "bOnErS" are all blocked (poor boners).
  95.                             privatesay(player, "YOU HAVE SAID EVIL THINGS.")
  96.                             return false
  97.                         end
  98.                     end
  99.                 end
  100.             end
  101.            
  102.     table.max(t)
  103.    
  104.         -- t: <table> Table you want to find the maximum value of.
  105.        
  106.         Returns:  Key which contains the maximum value as well as the maximum value.
  107.        
  108.         Example:
  109.        
  110.             function OnPlayerKill(killer, victim, mode)
  111.            
  112.                 local khash = gethash(killer)
  113.                 if humanweapon(killer) then  -- making up a function here to get to the point
  114.                     stats[khash].kills.humanweap = stats[khash].kills.humanweap + 1
  115.                 end
  116.                
  117.                 local weaptype, kills = table.max(stats[khash].kills)
  118.                 privatesay(killer, "You have the most kills with " .. weaptype .. ": " .. kills)
  119.             end
  120.            
  121.             >> You have the most kills with humanweap: 12
  122.            
  123.     table.maxv(t)
  124.    
  125.         -- See table.max; the only difference is this function only returns the maximum value, not the key at which it was found.
  126.        
  127.     table.maxes(t)
  128.    
  129.         -- t: <table> Table of which you would like to find the keys which have the maximum values.
  130.        
  131.         Returns:  A table of keys which all contain the maximum value of the table and the maximum value.
  132.        
  133.         Example:
  134.        
  135.             local t = {1, 2, 2, 5, 7, 2, 7, 3, 7, 7}
  136.             local keys, max = table.maxes(t)
  137.            
  138.             for k,v in ipairs(keys) do
  139.                 hprintf(v)
  140.             end
  141.            
  142.             hprintf("Max: " .. max)
  143.            
  144.             >> 5
  145.             >> 7
  146.             >> 9
  147.             >> 10
  148.             >> Max: 7
  149.            
  150.     table.sum(t)
  151.    
  152.         -- t: <table> Table of which you would like to find the sum of all numerical values.
  153.        
  154.         Returns:  Sum of all numerical values of the table specified and all tables nested within the table specified.
  155.        
  156.         Example:
  157.        
  158.             function OnPlayerKill(killer, victim, mode)
  159.            
  160.                 local khash = gethash(killer)
  161.                 local total_kills = table.sum(stats[khash].kills)
  162.                 privatesay(killer, "You have " .. total_kills .. " total kills.")
  163.             end
  164.            
  165.    
  166.     If you have any questions about how any of these functions work, PM me (Nuggets) at phasor.proboards.com.
  167. --]]
  168.  
  169. math.inf = 1 / 0
  170.  
  171. function table.save(t, filename)
  172.  
  173.     local dir = getprofilepath()
  174.     local file = io.open(dir .. "\\data\\" .. filename, "w")
  175.     local spaces = 0
  176.  
  177.     local function tab()
  178.  
  179.         local str = ""
  180.         for i = 1,spaces do
  181.             str = str .. " "
  182.         end
  183.  
  184.         return str
  185.     end
  186.  
  187.     local function format(t)
  188.  
  189.         spaces = spaces + 4
  190.         local str = "{ "
  191.  
  192.         for k,v in opairs(t) do
  193.             -- Key datatypes
  194.             if type(k) == "string" then
  195.                 k = string.format("%q", k)
  196.             elseif k == math.inf then
  197.                 k = "1 / 0"
  198.             end
  199.  
  200.             -- Value datatypes
  201.             if type(v) == "string" then
  202.                 v = string.format("%q", v)
  203.             elseif v == math.inf then
  204.                 v = "1 / 0"
  205.             end
  206.  
  207.             if type(v) == "table" then
  208.                 if table.len(v) > 0 then
  209.                     str = str .. "\n" .. tab() .. "[" .. k .. "] = " .. format(v) .. ","
  210.                 else
  211.                     str = str .. "\n" .. tab() .. "[" .. k .. "] = {},"
  212.                 end
  213.             else
  214.                 str = str .. "\n" .. tab() .. "[" .. k .. "] = " .. tostring(v) .. ","
  215.             end
  216.         end
  217.  
  218.         spaces = spaces - 4
  219.  
  220.         return string.sub(str, 1, string.len(str) - 1) .. "\n" .. tab() .. "}"
  221.     end
  222.  
  223.     file:write("return " .. format(t))
  224.     file:close()
  225. end
  226.  
  227. function table.load(filename)
  228.  
  229.     local dir = getprofilepath()
  230.     local file = loadfile(dir .. "\\data\\" .. filename)
  231.     if file then
  232.         return file() or {}
  233.     end
  234.    
  235.     return {}
  236. end
  237.  
  238. function table.len(t)
  239.  
  240.     local count = 0
  241.     for k,v in pairs(t) do
  242.         count = count + 1
  243.     end
  244.    
  245.     return count
  246. end
  247.  
  248. function table.find(t, v, case)
  249.  
  250.     if case == nil then case = true end
  251.  
  252.     for k,val in pairs(t) do
  253.         if case then
  254.             if v == val then
  255.                 return k
  256.             end
  257.         else
  258.             if string.lower(v) == string.lower(val) then
  259.                 return k
  260.             end
  261.         end
  262.     end
  263. end
  264.  
  265. function table.max(t)
  266.  
  267.     local max = -math.inf
  268.     local key
  269.    
  270.     for k,v in pairs(t) do
  271.         if tonumber(v) then
  272.             if tonumber(v) > max then
  273.                 key = k
  274.                 max = tonumber(v)
  275.             end
  276.         end
  277.     end
  278.    
  279.     return key,max
  280. end
  281.  
  282. function table.maxv(t)
  283.  
  284.     local max = -math.inf
  285.     local key
  286.    
  287.     for k,v in pairs(t) do
  288.         if tonumber(v) then
  289.             if tonumber(v) > max then
  290.                 key = k
  291.                 max = tonumber(v)
  292.             end
  293.         end
  294.     end
  295.    
  296.     return max 
  297. end
  298.  
  299. function table.maxes(t)
  300.  
  301.     local keys = {}
  302.     local max = -math.inf
  303.     for k,v in pairs(t) do
  304.         if tonumber(v) then
  305.             if tonumber(v) > max then
  306.                 max = tonumber(v)
  307.             end
  308.         end
  309.     end
  310.    
  311.     for k,v in pairs(t) do
  312.         if tonumber(v) == max then
  313.             table.insert(keys, k)
  314.         end
  315.     end
  316.    
  317.     return keys,max
  318. end
  319.  
  320. function table.sum(t, key)
  321.  
  322.     local sum = 0
  323.     for k,v in pairs(t) do
  324.         if type(v) == "table" then
  325.             sum = sum + table.sum(v, key)
  326.         elseif tonumber(v) then
  327.             if key then
  328.                 if key == k then
  329.                     sum = sum + tonumber(v)
  330.                 end
  331.             else
  332.                 sum = sum + tonumber(v)
  333.             end
  334.         end
  335.     end
  336.    
  337.     return sum
  338. end
  339.  
  340. -- Iterative Functions
  341.  
  342. --[[
  343.     Documentation:
  344.    
  345.     These are all iterative functions.  Iterative functions are used in loops (pairs and ipairs are two examples) and can be very useful if you want to loop through a table or numbers in a specific order.
  346.    
  347.     All of the following examples will be assuming the following table exists:
  348.    
  349.     t = {}
  350.     t[1] = 7
  351.     t[2] = 8
  352.     t[5] = -2
  353.     t["cheese"] = 10
  354.     t["derp"] = -14
  355.    
  356.     Here are descriptions of each function and how to use them:
  357.    
  358.     opairs
  359.    
  360.         Syntax:
  361.        
  362.             for k,v in opairs(t) do
  363.                 hprintf(k .. ": " .. v)
  364.             end
  365.        
  366.         When to use:
  367.        
  368.             -- The function opairs is short for "ordered pairs".  This iterative function will loop through all elements of a table (including string keys) in alphanumeric order.
  369.             -- Contrary to most beginning scripters' beliefs, ipairs does NOT do this.  ipairs loops through a table beginning at index 1 and adds 1 to the index until the value at the current index is nil.
  370.             -- Example of why this is useful:
  371.            
  372.                 for k,v in opairs(t) do
  373.                     hprintf(k .. ": " .. v)
  374.                 end
  375.                
  376.                 >> 1: 7
  377.                 >> 2: 8
  378.                 >> 5: -2
  379.                 >> cheese: 10
  380.                 >> derp: -14
  381.                
  382.                 for k,v in ipairs(t) do
  383.                     hprintf(k .. ": " .. v)
  384.                 end
  385.                
  386.                 >> 1: 7
  387.                 >> 2: 8
  388.                
  389.                 -- ipairs only prints up to key 2 because t[3] = nil.  All other keys are disregarded by ipairs.
  390.                
  391.     rpairs
  392.    
  393.         -- See opairs for details; rpairs is exactly the same, but loops in reverse order.
  394.        
  395.     expairs
  396.    
  397.         Syntax:
  398.        
  399.             for k,v in expairs(t, function(key, value) return true end)
  400.                 hprintf(k .. ": " .. v)
  401.             end
  402.        
  403.         When to use:
  404.        
  405.             -- expairs allows you to loop through a table while using a function to determine which keys and values the loop should consider.
  406.             -- For example:
  407.            
  408.                 -- Only loop through numerical keys
  409.                 for k,v in expairs(t, function(key, value) return type(key) == "number" end)
  410.                     hprintf(k .. ": " .. v)
  411.                 end
  412.                
  413.                 >> 1: 7
  414.                 >> 2: 8
  415.                 >> 5: -2
  416.                
  417.     irand
  418.    
  419.         Syntax:
  420.        
  421.             for i in irand(min, max) do
  422.                 hprintf(i)
  423.             end
  424.            
  425.         When to use:
  426.        
  427.             -- irand iterates from min to max in a random order.
  428.             -- Example:
  429.            
  430.                 for i in irand(0,15) do
  431.                     say(getname(i))
  432.                 end
  433.                
  434.                 >> Oxide
  435.                 >> Nuggets
  436.                 >> Wizard
  437.                 >> Chalonic
  438.                
  439.    
  440.     Iterative functions can be tricky, so let me know if you need help with any of them.  PM me (Nuggets) at phasor.proboards.com for any questions you have.
  441. --]]
  442.  
  443. function opairs(t)
  444.    
  445.     local keys = {}
  446.     for k,v in pairs(t) do
  447.         table.insert(keys, k)
  448.     end
  449.     table.sort(keys,
  450.     function(a,b)
  451.         if type(a) == "number" and type(b) == "number" then
  452.             return a < b
  453.         end
  454.         an = string.lower(tostring(a))
  455.         bn = string.lower(tostring(b))
  456.         if an ~= bn then
  457.             return an < bn
  458.         else
  459.             return tostring(a) < tostring(b)
  460.         end
  461.     end)
  462.     local count = 1
  463.     return function()
  464.         if table.unpack(keys) then
  465.             local key = keys[count]
  466.             local value = t[key]
  467.             count = count + 1
  468.             return key,value
  469.         end
  470.     end
  471. end
  472.  
  473. function rpairs(t)
  474.  
  475.     local keys = {}
  476.     for k,v in pairs(t) do
  477.         table.insert(keys, k)
  478.     end
  479.     table.sort(keys,
  480.     function(a,b)
  481.         if type(a) == "number" and type(b) == "number" then
  482.             return a > b
  483.         end
  484.         an = string.lower(tostring(a))
  485.         bn = string.lower(tostring(b))
  486.         if an ~= bn then
  487.             return an > bn
  488.         else
  489.             return tostring(a) > tostring(b)
  490.         end
  491.     end)
  492.     local count = 1
  493.     return function()
  494.         if table.unpack(keys) then
  495.             local key = keys[count]
  496.             local value = t[key]
  497.             count = count + 1
  498.             return key,value
  499.         end
  500.     end
  501. end
  502.  
  503. function expairs(t, fn)
  504.  
  505.     local keys = {}
  506.     for k,v in opairs(t) do
  507.         if fn(k,v) then
  508.             table.insert(keys, k)
  509.         end
  510.     end
  511.     local count = 1
  512.     return function()
  513.         if table.unpack(keys) then
  514.             local key = keys[count]
  515.             local value = t[key]
  516.             count = count + 1
  517.             return key,value
  518.         end
  519.     end
  520. end
  521.  
  522. function irand(min, max)
  523.  
  524.     local u = {}
  525.     for i = min,max do
  526.         table.insert(u, i)
  527.     end
  528.     return function()
  529.         if table.unpack(u) then
  530.             local rand = getrandomnumber(1, #u + 1)
  531.             local value = u[rand]
  532.             table.remove(u, rand)
  533.             return value
  534.         end
  535.     end
  536. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement