Advertisement
Niverton

screenAPI

Sep 12th, 2014
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.93 KB | None | 0 0
  1. --API for regions on advanced monitors
  2. --All local func are not meant to be usable from outside the file
  3.  
  4. --Returns a table containing a point's coordinates for use in addReg() (Makes it more readable)
  5. function p(x, y)
  6.     return {["x"]=x, ["y"]=y}
  7. end--p()
  8.  
  9. --Get the region's table from file
  10. local function getTable()
  11.     local t = {}
  12.     if fs.exists("data/regions") then
  13.         local f = fs.open("data/regions", 'r')
  14.         t = textutils.unserialize(f.readLine())
  15.         f.close()
  16.     end
  17.     return t
  18. end--getTable()
  19.  
  20. --Writes the table in file
  21. local function writeTable(t)
  22.     fs.makeDir("data")
  23.     local f = fs.open("data/regions", 'w')
  24.     f.writeLine(textutils.serialize(t))
  25.     f.close()
  26. end--writeTable
  27.  
  28. --Adds regions between A(x, y) and B(x2, y2)
  29. function addReg(n, A, B)
  30.     local t = getTable()
  31.    
  32.     --Adds a table inside the table
  33.     table.insert(t, {
  34.         ["name"]=n,
  35.         ["xS"]=A.x,
  36.         ["yS"]=A.y,
  37.         ["xE"]=B.x,
  38.         ["yE"]=B.y})
  39.    
  40.     writeTable(t)
  41. end --addReg()
  42.  
  43. --Deletes reg from list
  44. function delReg(n)
  45.     local t = getTable()
  46.     --Read table
  47.     for k,v in ipairs(t) do
  48.         --Find match
  49.         if v.name == n then
  50.             table.remove(t, k) --Delete the table from the list
  51.         end
  52.     end
  53.     writeTable(t)
  54. end --delReg()
  55.  
  56. --Clears the table
  57. function clear()
  58.     writeTable({})
  59. end--clear()
  60.  
  61. --Checks if a regions was clicked, must run in parralel with the other script
  62. function run()
  63.     local t, event, side, x, y
  64.     --Main loop
  65.     while true do
  66.         t = getTable()
  67.         event, side, x, y = os.pullEventRaw("monitor_touch") --Get screen event. We use Raw just in case the main program wants to use it to prevent the termination event
  68.         --Reads the table
  69.         for k,v in ipairs(t) do
  70.             --Search if we clicked in the region we're checking
  71.             if x >= v.xS and x <= v.xE and y >= v.yS and y <= v.yE then --We're in it
  72.                 --We queue  an event that will be read by the main script with the region's name
  73.                 os.queueEvent("regions", v.name)
  74.             end--If
  75.         end--For
  76.     end--while
  77. end--run
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement