Isigar

table helper

Jul 25th, 2021
836
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --- @param object object
  2. --- stolen: https://forums.coronalabs.com/topic/27482-copy-not-direct-reference-of-table/
  3. function deepCopy(object)
  4.     local lookup_table = {}
  5.     local function _copy(object)
  6.         if type(object) ~= "table" then
  7.             return object
  8.         elseif lookup_table[object] then
  9.             return lookup_table[object]
  10.         end
  11.         local new_table = {}
  12.         lookup_table[object] = new_table
  13.         for index, value in pairs(object) do
  14.             new_table[_copy(index)] = _copy(value)
  15.         end
  16.         return setmetatable(new_table, getmetatable(object))
  17.     end
  18.     return _copy(object)
  19. end
  20.  
  21. function table.len(table)
  22.     local count = 0
  23.     for _, _ in pairs(table) do
  24.         count = count + 1
  25.     end
  26.     return count
  27. end
  28.  
  29. function table.keys(t1)
  30.     local keys = {}
  31.     for key, _ in pairs(t1) do
  32.         table.insert(keys, key)
  33.     end
  34.     return keys
  35. end
  36.  
  37. function table.values(t1)
  38.     local values = {}
  39.     for _, value in pairs(t1) do
  40.         table.insert(values, value)
  41.     end
  42.     return values
  43. end
  44.  
  45. function table.random(t1)
  46.     local randomIndex = math.random(1, table.len(t1))
  47.     return t1[randomIndex]
  48. end
  49.  
  50. --- @param sourceTable table
  51. --- @param targetTable table
  52. --- @return table
  53. --- stolen: https://stackoverflow.com/questions/1283388/lua-merge-tables
  54. function table.merge(t1, t2)
  55.     local target = deepCopy(t1)
  56.     local source = deepCopy(t2)
  57.     for k, v in pairs(source) do
  58.         if (type(v) == "table") and (type(target[k] or false) == "table") then
  59.             mergeTables(target[k], source[k])
  60.         else
  61.             target[k] = v
  62.         end
  63.     end
  64.     return target
  65. end
  66.  
  67. --- @param table table
  68. --- @return boolean
  69. function table.isEmpty(table)
  70.     if isTable(table) then
  71.         if next(table) == nil then
  72.             return true
  73.         else
  74.             return false
  75.         end
  76.     else
  77.         return true
  78.     end
  79. end
  80.  
RAW Paste Data