SHARE
TWEET

ComputerCraft Tutorial: h2peripheral_API 0_1

hevohevo Jan 22nd, 2014 818 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- ###############################
  2. -- h2peripheral API
  3. -- version 0.1
  4. -- http://hevohevo.hatenablog.com/
  5. -- Write in your program.
  6. --    os.loadAPI("h2peripheral")
  7.  
  8. os.loadAPI("rom/apis/peripheral") -- to make sure
  9.  
  10. if rs and peripheral and os then
  11.   local types = {                   -- White-list
  12.     drive="Disk Drive",
  13.     monitor="Monitor and  Advanced Monitor",
  14.     advanced_monitor="Advanced Monitor",
  15.     modem="Wired Modem and Wireless Modem",
  16.     wireless_modem="Wireless Modem",
  17.     workbench="Crafty Turtle's workbench",
  18.     printer="Printer",
  19.     command="Command Block"
  20.   }
  21.  
  22.   function wrapByName(str)
  23.     if not types[str] then return false end --  check with White-list
  24.  
  25.     local f_tbl = nil
  26.     for _,side in pairs(rs.getSides()) do   --  search valid sides
  27.       local type_name = peripheral.getType(side)
  28.  
  29.       --  "drive", "monitor", "modem", "workbench", "printer", "command"
  30.       if type_name == str then  
  31.         f_tbl = peripheral.wrap(side)
  32.         f_tbl.side = side
  33.         break
  34.       elseif str == "advanced_monitor" and type_name == "monitor" and peripheral.call(side, "isColor") then
  35.         f_tbl = peripheral.wrap(side)
  36.         f_tbl.side = side
  37.         break
  38.       elseif str == "wireless_modem" and type_name == "modem" and peripheral.call(side, "isWireless") then
  39.         f_tbl = peripheral.wrap(side)
  40.         f_tbl.side = side
  41.         break
  42.       end
  43.     end
  44.     return f_tbl
  45.   end
  46.  
  47.   function wrap(str) -- selector
  48.     local f_tbl = nil
  49.     if types[str] then       -- types
  50.       f_tbl = wrapByName(str)
  51.     else                     -- sides and the others
  52.       f_tbl = peripheral.wrap(str)
  53.       if f_tbl then f_tbl.side = str end
  54.     end
  55.     return f_tbl
  56.   end
  57.  
  58.   function waitForDetect(str)
  59.     local f_tbl = nil
  60.     repeat
  61.       f_tbl = wrap(str)
  62.       if not f_tbl then os.pullEvent("peripheral") end
  63.     until f_tbl
  64.    
  65.     return f_tbl
  66.   end
  67.  
  68. end
  69.  
  70. --[[
  71. local tmp1 = waitForDetect("wireless_modem")
  72. local tmp2 = waitForDetect("advanced_monitor")
  73.  
  74. for k,v in pairs(tmp1) do
  75.   print(k,' = ',v)
  76. end
  77. --]]
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top