Operating system for OpenComputers
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

66 wiersze
1.3KB

  1. do
  2. _G.fd,_G.io = {},{}
  3. function io.write(d) -- writes *d* to stdout
  4. fd[os.getenv("t") or 1].write(d)
  5. end
  6. function io.read(d,b) -- reads *d* from stdin, until something is returned, or b is true
  7. local r = ""
  8. repeat
  9. r=fd[os.getenv("t") or 1].read(d)
  10. coroutine.yield()
  11. until r or b
  12. return r
  13. end
  14. function print(...) -- outputs its arguments to stdout, separated by newlines
  15. for k,v in pairs({...}) do
  16. io.write(tostring(v).."\n")
  17. end
  18. end
  19. local function fdw(f,d)
  20. fd[f.fd].write(d)
  21. end
  22. local function fdr(f,d)
  23. return fd[f.fd].read(d)
  24. end
  25. local function fdc(f)
  26. fd[f.fd].close()
  27. fd[f.fd] = nil
  28. end
  29. function io.newfd() -- creates a new file descriptor and returns it plus its ID
  30. local nfd=#fd+1
  31. fd[nfd] = {}
  32. return nfd,fd[nfd]
  33. end
  34. local function fdfile(f,m) -- create a fd from a file
  35. local e,fobj = pcall(fs.open,f,m)
  36. if e and fobj then
  37. local fdi, fdo =io.newfd()
  38. if fobj.read then
  39. function fdo.read(d)
  40. return fobj:read(d)
  41. end
  42. end
  43. if fobj.write then
  44. function fdo.write(d)
  45. return fobj:write(d)
  46. end
  47. end
  48. function fdo.close()
  49. fobj:close()
  50. end
  51. return fdi
  52. end
  53. return false
  54. end
  55. function io.open(f,m) -- opens file or file descriptor *f* with mode *m*
  56. if type(f) == "string" then
  57. f = fdfile(f,m)
  58. end
  59. if fd[f] then
  60. local t = {["close"]=fdc,["read"]=fdr,["write"]=fdw,["fd"]=f,["mode"]=m}
  61. return t
  62. end
  63. return false
  64. end
  65. end