Advertisement
Squil3lx

TableUtils

Aug 20th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.57 KB | None | 0 0
  1. local api = {}
  2.  
  3. function api.isTable(o)
  4.     return type(o) == "table"
  5. end
  6.  
  7. function api.hasKey(tbl, target)
  8.     if tbl[target] ~= nil then
  9.         return true
  10.     end
  11.  
  12.     -- key might exist but set to nil value
  13.     for key, _ in pairs(tbl) do
  14.         if key == target then
  15.             return true
  16.         end
  17.     end
  18.  
  19.     return false
  20. end
  21.  
  22. function api.hasValue(tbl, target)
  23.     for _, value in pairs(tbl) do
  24.         if value == target then
  25.             return true
  26.         end
  27.     end
  28.  
  29.     return false
  30. end
  31.  
  32. function api.size(tbl)
  33.     count = 0
  34.     for _ in pairs(tbl) do count = count + 1 end
  35.     return count
  36. end
  37.  
  38. function api.print(tbl, level)
  39.     level = (type(level) == "number") and level or 1
  40.     if api.isTable(tbl) then
  41.         local s = "{"
  42.         if api.size(tbl) > 0 then
  43.             for k, v in pairs(tbl) do
  44.                 if not api.isTable(k) then
  45.                     k = "\""..(k ~= nil and tostring(k) or "nil").."\""
  46.                 else
  47.                     k = api.print(k, level + 1)
  48.                 end
  49.                 s = s.."\n"..(string.rep("\t", level))..""..k.." = "..api.print(v, level + 1)..","
  50.             end
  51.         else
  52.             return "{}"
  53.         end
  54.  
  55.         return s.."\n"..(string.rep("\t", level - 1)).."}"
  56.     else
  57.         return tostring(tbl)
  58.     end
  59. end
  60.  
  61. local index = {}
  62. local metatable = {
  63.     __index = function(t, k)
  64.         -- print("*access to element "..tostring(k))
  65.         return t[index][k]
  66.     end,
  67.     __newindex = function(t, k, v)
  68.         -- print("*update of element "..tostring(k).." to "..tostring(v))
  69.         t[index][k] = v
  70.     end
  71. }
  72.  
  73. function api.proxy(tbl)
  74.     local proxy = {}
  75.     proxy[index] = tbl
  76.     setmetatable(proxy, metatable)
  77.     return proxy, metatable
  78. end
  79.  
  80. return api
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement