Operating system for OpenComputers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
2.1KB

  1. do
  2. io = {}
  3. function io.close(file)
  4. return (file or io.output()):close()
  5. end
  6. function io.flush()
  7. return io.output():flush()
  8. end
  9. function io.lines(filename, ...)
  10. if filename then
  11. local file, reason = io.open(filename)
  12. if not file then
  13. error(reason, 2)
  14. end
  15. local args = table.pack(...)
  16. return function()
  17. local result = table.pack(file:read(table.unpack(args, 1, args.n)))
  18. if not result[1] then
  19. if result[2] then
  20. error(result[2], 2)
  21. else -- eof
  22. file:close()
  23. return nil
  24. end
  25. end
  26. return table.unpack(result, 1, result.n)
  27. end
  28. else
  29. return io.input():lines()
  30. end
  31. end
  32. function io.open(path, mode)
  33. local stream, result = fs.open(path, mode)
  34. if stream then
  35. return buffer.new(mode, stream)
  36. else
  37. return nil, result
  38. end
  39. end
  40. local fdt = {[0]="STDIN","STDOUT","STDERR"}
  41. local function getfh(fd)
  42. return os.getenv(fdt[fd] or "FILE"..tostring(fd))
  43. end
  44. local function setfh(fd,fh)
  45. os.setenv(fdt[fd] or "FILE"..tostring(fd),fh)
  46. end
  47. function io.stream(fd,file,mode)
  48. checkArg(1,fd,'number')
  49. assert(fd>=0,'fd must be >= 0. 0 is input, 1 is stdout, 2 is stderr')
  50. if file then
  51. if type(file) == "string" then
  52. local result, reason = io.open(file, mode)
  53. if not result then
  54. error(reason, 2)
  55. end
  56. file = result
  57. elseif not io.type(file) then
  58. error("bad argument #1 (string or file expected, got " .. type(file) .. ")", 2)
  59. end
  60. setfh(fd,file)
  61. end
  62. return getfh(fd)
  63. end
  64. function io.input(file)
  65. return io.stream(0, file, 'r')
  66. end
  67. function io.output(file)
  68. return io.stream(1, file,'w')
  69. end
  70. function io.error(file)
  71. return io.stream(2, file,'w')
  72. end
  73. function io.read(...)
  74. return io.input():read(...)
  75. end
  76. function io.tmpfile()
  77. local name = os.tmpname()
  78. if name then
  79. return io.open(name, "a")
  80. end
  81. end
  82. function io.type(object)
  83. if type(object) == "table" then
  84. if getmetatable(object) == "file" then
  85. if object.stream.handle then
  86. return "file"
  87. else
  88. return "closed file"
  89. end
  90. end
  91. end
  92. return nil
  93. end
  94. function io.write(...)
  95. return io.output():write(...)
  96. end
  97. function print(...)
  98. for k,v in ipairs({...}) do
  99. io.write(tostring(v).."\n")
  100. end
  101. end
  102. end