CreeperNukeBoom

CGBCoreLib

Jan 19th, 2020 (edited)
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.59 KB | None | 0 0
  1. --CreeperGoBoom (CGB) Core Library API
  2. --A bunch of useful functions
  3.  
  4. local funcs = {}
  5.  
  6. function funcs.round(number, decimals)
  7.     local multiplier = 10 ^ decimals
  8.     return math.floor(number * multiplier + 0.5) / multiplier
  9. end
  10.  
  11. --An Intro  Function
  12. function funcs.greeting(stringProgName,boolTimed)
  13.     if boolTimed == nil then
  14.         boolTimed = true
  15.     end
  16.     term.clear()
  17.     term.setCursorPos(1,1)
  18.     print("BLUTEK Industries")
  19.     if boolTimed then sleep(0.5) end
  20.     print("Making tomorrow, today")
  21.     if boolTimed then sleep(0.5) end
  22.     print("Because. We. Can!")
  23.     if boolTimed then sleep(0.25) end
  24.     print(" ")
  25.     print("loading: "..stringProgName)
  26.     print("Done!")
  27.     if boolTimed then sleep(0.25) end
  28. end
  29.  
  30. function funcs.typeText(stringText,numberCharDelay)
  31.  
  32. end
  33.  
  34. --Simplifies an energy reading into its k, m, g etc by returning a simplified string
  35. function funcs.simplifyReading(stringUnit, numberInput, decimals)
  36.     if type(numberInput) ~= "number" then
  37.         print("error:simplifyReading: not a valid number!")
  38.         return
  39.     end
  40.  
  41.     decimals = decimals or 2
  42.  
  43.     local type = ""
  44.     local number = numberInput
  45.  
  46.     local units = {
  47.         { divisor = 1e18, type = "Qi"},
  48.         { divisor = 1e15, type = "Q" },
  49.         { divisor = 1e12, type = "T" },
  50.         { divisor = 1e9, type = "B" },
  51.         { divisor = 1e6, type = "M" },
  52.         { divisor = 1e3, type = "K" }
  53.     }
  54.  
  55.     for _, unit in ipairs(units) do
  56.         if numberInput >= unit.divisor then
  57.             type = unit.type
  58.             number = numberInput / unit.divisor
  59.             break
  60.         end
  61.     end
  62.  
  63.     --determine if the reading will have decimals based on if over 100 or not for monitor display.
  64.     If number >= 100 then
  65.       decimals = 0
  66.     end
  67.  
  68.     number = funcs.round(number, decimals)
  69.  
  70.     local output = number .. type .. stringUnit
  71.     return output
  72. end
  73.  
  74.  
  75. --creates a table of peripherals matching inserted method names
  76. function funcs.cataloguePeripherals(...)
  77.     local grid = {}
  78.     local requiredMethods = {...}
  79.     for _, name in ipairs(peripheral.getNames()) do
  80.         local availableMethods = peripheral.getMethods(name)
  81.         local hasMethod = {}
  82.        
  83.         --Create a quick lookup table of of available methods
  84.         for _, method in ipairs(availableMethods) do
  85.             hasMethod[method] = true
  86.         end
  87.        
  88.         --Assume the peripheral qualifies
  89.         local matches = true
  90.        
  91.         --Check every method requested by caller
  92.         for _, requiredMethod in ipairs(requiredMethods) do
  93.             if not hasMethod[requiredMethod] then
  94.                 matches = false
  95.                 break
  96.             end
  97.         end
  98.        
  99.         --add peripheral if it has all required methods
  100.         if matches then
  101.             table.insert(grid,name)
  102.         end
  103.     end
  104.    
  105.     return grid
  106. end
  107.    
  108.    
  109.    
  110. local doOnceNoColorWarning = {
  111.   ["colorPrint"] = true,
  112.   ["errorPrint"] = true
  113. }  -- For displaying a one time warning about no color capability
  114.  
  115.  
  116. --Writes data to a file, data can be anything except a function
  117. function funcs.fileWrite(stringFileName,data)
  118.   local file = fs.open(stringFileName, "w")
  119.   file.write(data)
  120.   file.close()
  121. end
  122.  
  123. --Gets user input for a prompt
  124. --possibly completely unneccessary
  125. function funcs.getUserInput(stringPrompt)  
  126.   print(stringPrompt)
  127.   local result = io.read()
  128.   return result
  129. end
  130.  
  131. function funcs.checkAnswerPrompt(stringPrompt, tableAnswers, boolRepeatUntilCorrect, boolShowAnswers)
  132.  
  133.  
  134. end
  135.  
  136.  
  137. --Checks a string against a table of answers and prints available answers if incorrect
  138. function funcs.checkAnswer(stringInput,tableAnswers)
  139.   for _, key in pairs(tableAnswers) do
  140.     if key == stringInput then
  141.       return true
  142.     end
  143.   end
  144.   print("Answer not available, please use one of: ", table.concat(tableAnswers, ", "), ".")
  145.   return false
  146. end
  147.  
  148. --Checks a string against a table of answers. No feedback
  149. function funcs.checkAnswerSilent(stringInput, tableAnswers)
  150.   for _, key in pairs(tableAnswers) do
  151.     if key == stringInput then
  152.       return true
  153.     end
  154.   end
  155.   return false
  156. end
  157.  
  158. --Gets user input and checks input against answer table. repeats until answered correctly.
  159. function funcs.getAnswer(stringPrompt, tableAnswers)  
  160.   local input
  161.   repeat
  162.     input = funcs.getUserInput(stringPrompt)
  163.   until funcs.checkAnswer(input, tableAnswers)
  164.   return input
  165. end
  166.  
  167. --Gets user input and checks against answer table while showing available answers in prompt
  168. function funcs.getAnswerWithPrompts(stringPrompt, tableAnswers)
  169.   local input
  170.   repeat
  171.     input = funcs.getUserInput(stringPrompt .. " " .. table.concat(tableAnswers, ", "), ".")
  172.   until funcs.checkAnswer(input, tableAnswers)
  173.   return input
  174. end
  175.  
  176. --Returns wrap if peripheral name found
  177. function funcs.findPeripheral(stringName,stringAltName)  
  178.   if type(stringName) ~= "string" then return end
  179.   if type(stringAltName) ~= "string" then return end
  180.   return peripheral.find(stringName) or peripheral.wrap(stringAltName)
  181. end
  182.  
  183. --Returns entered name or altname if peripheral found
  184. function funcs.peripheralCheck(stringName, stringAltName)
  185.   if type(stringName) ~= "string" then return end
  186.   if type(stringAltName) ~= "string" then return end
  187.   if peripheral.find(stringName) then return stringName elseif peripheral.wrap(stringAltName) then return stringAltName end
  188. end
  189.  
  190. --Returns a table of all connected peripheral names containing Name
  191. --Function idea by FatBoyChummy
  192. function funcs.getPeripherals(stringName)
  193.   local peripherals = {}
  194.   local n = 0
  195.   for _, name in pairs(peripheral.getNames()) do
  196.     if name:find(stringName) then
  197.       n = n + 1
  198.       peripherals[n] = name
  199.     end
  200.   end
  201.   return peripherals
  202. end
  203.  
  204. --Returns a table of color names as string
  205. function funcs.getColorNames()
  206.   local doNotAddIfContain = {"test","pack","rgb","combine","subtract"}
  207.   local colorNames = {}
  208.   local doNotAdd = false
  209.   for k, v in pairs(colors) do
  210.     for _ , check in pairs(doNotAddIfContain) do
  211.       if k:find(check) then  --check k against list of do not adds.
  212.         doNotAdd = true
  213.         break
  214.       end
  215.     end
  216.     if not doNotAdd then
  217.       table.insert(colorNames,k)      -- Test did not find a match in do not add, add checked color name.
  218.     else
  219.       doNotAdd = false   -- Test found a match containing a do not add. Reset for next check.
  220.     end  
  221.   end
  222.   return colorNames
  223. end
  224.  
  225. local colorNamesList = funcs.getColorNames()
  226.  
  227. function funcs.loadConfig(configFileName)
  228.   local file = fs.open(configFileName, "r")
  229.   local fData = file.readAll()
  230.   local config = textutils.unserialize(fData)
  231.   file.close()
  232.   return config
  233. end
  234.  
  235. function funcs.saveConfig(configFileName,data)
  236.   local sData = textutils.serialize(data)
  237.   funcs.fileWrite(configFileName,sData)
  238. end
  239.  
  240. function funcs.tablePrint(tableVar)
  241.   if tableVar then local sData = textutils.serialize(tableVar)
  242.   print(sData)
  243.   end
  244. end
  245.  
  246. function funcs.getTableSize(table)
  247.   local count = 0
  248.   for i , _ in pairs(table) do
  249.     count = count + 1
  250.   end
  251.   return count
  252. end
  253.  
  254. function funcs.getAnswerAsNumbers(stringPrompt,tableAnswers) --returns answer chosen from table.
  255.   --Lists entries
  256.   local answer
  257.   local tableVar = {} --stores key and value depending if key is a number or not
  258.   repeat
  259.     local count = 0
  260.     print(stringPrompt)
  261.     for key , value in pairs(tableAnswers) do
  262.       if type(key) == "number" then --key isnt always a number
  263.         print(key,value)
  264.         tableVar[key]=value --What you see come up on screen is what is saved.
  265.       else
  266.         count = count + 1
  267.         print(count,key)
  268.         tableVar[count]=key
  269.       end
  270.     end
  271.     print("Please enter the corresponding number for your selection.")
  272.     answer = tonumber(io.read())
  273.     if answer then          --Answer must be a number else it is a string
  274.       if answer > funcs.getTableSize(tableVar) then
  275.         print("That's out of range, please try again!")
  276.       end
  277.     else  --in case someone enters something other than a number
  278.       print("That's not a number. Please only answer with a number!")
  279.     end
  280.   until answer and answer <= funcs.getTableSize(tableVar)  --must have this check else it will error if answer is string
  281.   return tableVar[answer]
  282. end
  283.  
  284. function funcs.getAnswerAsNumbersGrouped(stringPrompt,tableAnswers) --returns answer chosen from table.
  285.   --groups entries as per num per line, recommend no more than 3
  286.   local answer
  287.   local tableVar = {}  --creates a searchable table. since not all tables that are entered have numbers as keys
  288.   local tableVarNumbered = {}
  289.   repeat
  290.     local count = 0
  291.     print(stringPrompt)
  292.     for key , value in pairs(tableAnswers) do
  293.       if type(key) == "number" then --key isnt always a number
  294.         tableVar[key] = value --What you see come up on screen is what is saved.
  295.         tableVarNumbered[key] = key .. " " .. value
  296.       else
  297.         count = count + 1
  298.         tableVar[count] = key
  299.         tableVarNumbered[count] = count .. " " .. key
  300.       end
  301.     end
  302.     local tableSize = funcs.getTableSize(tableVar)
  303.     textutils.tabulate(tableVarNumbered)
  304.     print("Please enter the corresponding number for your selection.")
  305.     answer = tonumber(io.read())
  306.     if answer then          --Answer must be a number else it is a string
  307.       if answer > tableSize then
  308.         print("That's out of range, please try again!")
  309.       end
  310.     else  --in case someone enters something other than a number
  311.       print("That's not a number. Please only answer with a number!")
  312.     end
  313.   until answer and answer <= tableSize  --must have this check else it will error if answer is string
  314.   return tableVar[answer]
  315. end
  316.  
  317. function funcs.findPeripheralOnSide(stringPeripheral) --returns side. Ignores peripherals behind modems etc.
  318.   local sides = redstone.getSides()
  319.   for _ , side in pairs(sides) do
  320.     if peripheral.getType(side) == stringPeripheral then
  321.       local peripheralSide = side --This is needed for check below
  322.       return side
  323.     end
  324.   end
  325.   if not peripheralSide then  --peripheral not found as such is nil
  326.     return nil
  327.   end
  328. end
  329.  
  330. function funcs.peripheralCall(stringName,stringMethod,...)  --An enhanced peripheral.call
  331.   --Can check for name or side
  332.   --Also checks network for peripheral
  333.   local periph = peripheral.wrap(stringName)
  334.   -- Check that stringName peripheral exists
  335.   if not periph then
  336.     error("'" .. stringName .. "' is not a peripheral, check spelling and try again.")
  337.   end
  338.   -- Check that peripheral supports stringMethod
  339.   if not periph[stringMethod] then
  340.     print("'" .. stringName .. "' Methods:")
  341.     print(textutils.pagedTabulate(peripheral.getMethods(stringName)))
  342.     error("'" .. stringMethod .. "' is not a method of: '" .. stringName .. "', check method names listed above and try again.")
  343.   else
  344.   -- Peripheral exists and method supported, run it.
  345.     periph[stringMethod](...)
  346.     periph = nil   --peripheral interaction successful. clear wrap from memory
  347.   end
  348. end
  349.  
  350. -- A simplified table.insert
  351. function funcs.tableInsert(tableVar,numOrStringKey,value)
  352.   if type(value) == "nil"  then
  353.     table.insert(tableVar,numOrStringKey)
  354.   else
  355.     local key = numOrStringKey or #tableVar + 1
  356.     tableVar[key]=value
  357.   end
  358. end
  359.  
  360. function funcs.colorPrint(stringColorName,string)
  361.   if term.isColor() then
  362.     if not pcall(term.setTextColour,colors[stringColorName]) then
  363.       print(textutils.pagedTabulate(colorNamesList))
  364.       error("Error: colorPrint: incorrect color name entered: '" .. stringColorName .. "'. please check with above list")
  365.     else
  366.       print(string)
  367.       term.setTextColour(colors.white)
  368.     end
  369.   else
  370.     if doOnceNoColorWarning.colorPrint == true then
  371.       print("Warning: colorPrint: Cannot output color here! This message only shows once!")
  372.       doOnceNoColorWarning.colorPrint = false
  373.     end
  374.     print(string)
  375.   end
  376. end
  377.  
  378. function funcs.errorPrint(string)
  379.   if term.isColor() then
  380.     term.setTextColour(colors.red)
  381.     print(string)
  382.     term.setTextColour(colors.white)
  383.   else
  384.     if doOnceNoColorWarning.errorPrint == true then
  385.       print("Warning: errorPrint: Cannot output color here! This message only shows once!")
  386.       doOnceNoColorWarning.errorPrint = false
  387.     end
  388.     print(string)
  389.   end
  390. end
  391.  
  392. --Checks a string against a list of strings. Only returns true or false
  393. function funcs.isInList(stringToCheck,tableList)
  394.   local isListed = false
  395.   for k,v in pairs(tableList) do
  396.     if v == stringToCheck then
  397.       isListed = true
  398.       return true
  399.     end
  400.   end
  401.   if not isListed then
  402.     return false
  403.   end
  404. end
  405.  
  406. --Turns a string into a table
  407. --ignores non alphanumeric chars
  408. function funcs.stringToTable(stringInput)
  409.   local tableOutput = {}
  410.   local n=0
  411.   for i in string.gmatch(stringInput, "%w+") do
  412.     n = n+1
  413.     tableOutput[n] = i
  414.   end
  415.   return tableOutput
  416. end
  417.  
  418. --Turns a string into a table
  419. --ignores only spaces
  420. function funcs.stringToTable(stringInput)
  421.   local tableOutput = {}
  422.   local n=0
  423.   for i in string.gmatch(stringInput, "%S+") do
  424.     n = n+1
  425.     tableOutput[n] = i
  426.   end
  427.   return tableOutput
  428. end
  429.  
  430. --Splits a string into seperate vars
  431. --Example: this, string = stringToVars("this string")
  432. --ignores non alphanumeric characters and counts them as spaces (-=+:;>?/) etc
  433. function funcs.stringToVars(stringInput)
  434.   local tableOutput = {}
  435.   local n=0
  436.   for i in string.gmatch(stringInput, "%w+") do
  437.     n = n+1
  438.     tableOutput[n] = i
  439.   end
  440.   return table.unpack(tableOutput)
  441. end
  442.  
  443. --Splits a string into seperate vars
  444. --Example: this, string = stringToVars("this string")
  445. --More inclusive, only ignores spaces
  446. function funcs.stringToVarsAll(stringInput)
  447.   local tableOutput = {}
  448.   local n=0
  449.   for i in string.gmatch(stringInput, "%S+") do
  450.     n = n+1
  451.     tableOutput[n] = i
  452.   end
  453.   return table.unpack(tableOutput)
  454. end
  455.  
  456. return funcs
Advertisement
Add Comment
Please, Sign In to add comment