Feliiiiip

flippy-utils.lua

May 3rd, 2022 (edited)
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.07 KB | None | 0 0
  1. local pretty = require("cc.pretty")
  2. local fUtils = {}
  3.  
  4.  
  5. -- Basic Utils
  6. fUtils.writeC = function(color, str)
  7.     local oldTextColor = term.getTextColor()
  8.     term.setTextColor(color)
  9.     write(str)
  10.     term.setTextColor(oldTextColor)
  11. end
  12.  
  13. fUtils.printC = function(color, ...)
  14.     local oldTextColor = term.getTextColor()
  15.     term.setTextColor(color)
  16.     print(...)
  17.     term.setTextColor(oldTextColor)
  18. end
  19.  
  20. fUtils.formatTime = function(sec)
  21.     local date = os.date("!*t", sec)
  22.     if sec >= 3600 then
  23.         return ("%02d:%02d:%02d"):format(date.hour, date.min, date.sec)
  24.     else
  25.         return ("%02d:%02d"):format(date.min, date.sec)
  26.     end
  27. end
  28.  
  29. -- Peripheral Utils
  30. fUtils.peripheral = {}
  31.  
  32. fUtils.peripheral.wrapAll = function(type)
  33.     local group = {}
  34.     local allPeripheralNames = peripheral.getNames()
  35.     for _, name in ipairs(allPeripheralNames) do
  36.         if peripheral.getType(name) == type then
  37.             group[name] = peripheral.wrap(name)
  38.         end
  39.     end
  40.  
  41.     assert(fUtils.table.size(group) > 1, "No peripherals of given type found.")
  42.  
  43.     local peripheralNames = fUtils.table.getKeys(group)
  44.     local methodNames = peripheral.getMethods(peripheralNames[1])
  45.     for _, method in ipairs(methodNames) do
  46.         group[method] = function(...)
  47.             local ret
  48.             for _, name in ipairs(peripheralNames) do
  49.                 local _ret = group[name][method](table.unpack(arg))
  50.                 if ret == nil then ret = _ret else ret = ret and _ret end
  51.             end
  52.             return ret
  53.         end
  54.     end
  55.     return group
  56. end
  57.  
  58.  
  59. -- Table Utils
  60. fUtils.table = {}
  61.  
  62. fUtils.table.getKeys = function(t)
  63.     local keys={}
  64.     for key,_ in pairs(t) do
  65.         table.insert(keys, key)
  66.     end
  67.     return keys
  68. end
  69.  
  70. fUtils.table.getValues = function(t)
  71.     local vals={}
  72.     for _,val in pairs(t) do
  73.         table.insert(vals, val)
  74.     end
  75.     return vals
  76. end
  77.  
  78. fUtils.table.print = function(t)
  79.     pretty.pretty_print(t)
  80. end
  81.  
  82. fUtils.table.size = function(t)
  83.     return #fUtils.table.getKeys(t)
  84. end
  85.  
  86. return fUtils
Add Comment
Please, Sign In to add comment