Advertisement
joebodo

sys.apis.minify.Util.lua

Sep 6th, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.84 KB | None | 0 0
  1.  
  2. --
  3. -- Util.lua
  4. --
  5. -- Provides some common utilities shared throughout the project.
  6. --
  7.  
  8. local function lookupify(tb)
  9.     for _, v in pairs(tb) do
  10.         tb[v] = true
  11.     end
  12.     return tb
  13. end
  14.  
  15.  
  16. local function CountTable(tb)
  17.     local c = 0
  18.     for _ in pairs(tb) do c = c + 1 end
  19.     return c
  20. end
  21.  
  22.  
  23. local function PrintTable(tb, atIndent)
  24.     if tb.Print then
  25.         return tb.Print()
  26.     end
  27.     atIndent = atIndent or 0
  28.     local useNewlines = (CountTable(tb) > 1)
  29.     local baseIndent = string.rep('    ', atIndent+1)
  30.     local out = "{"..(useNewlines and '\n' or '')
  31.     for k, v in pairs(tb) do
  32.         if type(v) ~= 'function' then
  33.         --do
  34.             out = out..(useNewlines and baseIndent or '')
  35.             if type(k) == 'number' then
  36.                 --nothing to do
  37.             elseif type(k) == 'string' and k:match("^[A-Za-z_][A-Za-z0-9_]*$") then
  38.                 out = out..k.." = "
  39.             elseif type(k) == 'string' then
  40.                 out = out.."[\""..k.."\"] = "
  41.             else
  42.                 out = out.."["..tostring(k).."] = "
  43.             end
  44.             if type(v) == 'string' then
  45.                 out = out.."\""..v.."\""
  46.             elseif type(v) == 'number' then
  47.                 out = out..v
  48.             elseif type(v) == 'table' then
  49.                 out = out..PrintTable(v, atIndent+(useNewlines and 1 or 0))
  50.             else
  51.                 out = out..tostring(v)
  52.             end
  53.             if next(tb, k) then
  54.                 out = out..","
  55.             end
  56.             if useNewlines then
  57.                 out = out..'\n'
  58.             end
  59.         end
  60.     end
  61.     out = out..(useNewlines and string.rep('    ', atIndent) or '').."}"
  62.     return out
  63. end
  64.  
  65.  
  66. local function splitLines(str)
  67.     if str:match("\n") then
  68.         local lines = {}
  69.         for line in str:gmatch("[^\n]*") do
  70.             table.insert(lines, line)
  71.         end
  72.         assert(#lines > 0)
  73.         return lines
  74.     else
  75.         return { str }
  76.     end
  77. end
  78.  
  79.  
  80. local function printf(fmt, ...)
  81.     return print(string.format(fmt, ...))
  82. end
  83.  
  84.  
  85. return {
  86.     PrintTable = PrintTable,
  87.     CountTable = CountTable,
  88.     lookupify  = lookupify,
  89.     splitLines = splitLines,
  90.     printf     = printf,
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement