2018-11-02 12:05:41 -04:00
|
|
|
do
|
2019-01-08 02:02:39 -05:00
|
|
|
_G.fd,_G.io = {},{}
|
|
|
|
function io.write(d) -- writes *d* to stdout
|
|
|
|
fd[os.getenv("t") or 1].write(d)
|
2018-11-02 12:05:41 -04:00
|
|
|
end
|
2019-01-08 22:09:57 -05:00
|
|
|
function io.read(d,b) -- reads *d* from stdin, until something is returned, or b is true
|
2018-11-02 12:05:41 -04:00
|
|
|
local r = ""
|
|
|
|
repeat
|
2019-01-08 02:02:39 -05:00
|
|
|
r=fd[os.getenv("t") or 1].read(d)
|
2018-11-02 12:05:41 -04:00
|
|
|
coroutine.yield()
|
|
|
|
until r or b
|
|
|
|
return r
|
|
|
|
end
|
2019-01-08 02:02:39 -05:00
|
|
|
function print(...) -- outputs its arguments to stdout, separated by newlines
|
2018-11-02 12:05:41 -04:00
|
|
|
for k,v in pairs({...}) do
|
|
|
|
io.write(tostring(v).."\n")
|
|
|
|
end
|
|
|
|
end
|
2019-01-08 02:02:39 -05:00
|
|
|
local function fdw(f,d)
|
|
|
|
fd[f.fd].write(d)
|
|
|
|
end
|
|
|
|
local function fdr(f,d)
|
|
|
|
return fd[f.fd].read(d)
|
|
|
|
end
|
|
|
|
local function fdc(f)
|
|
|
|
fd[f.fd].close()
|
|
|
|
fd[f.fd] = nil
|
2018-11-02 12:05:41 -04:00
|
|
|
end
|
2019-01-08 06:11:49 -05:00
|
|
|
function io.newfd() -- creates a new file descriptor and returns it plus its ID
|
2019-01-08 02:02:39 -05:00
|
|
|
local nfd=#fd+1
|
|
|
|
fd[nfd] = {}
|
|
|
|
return nfd,fd[nfd]
|
|
|
|
end
|
2019-01-09 00:15:31 -05:00
|
|
|
local function fdfile(f,m) -- create a fd from a file
|
|
|
|
local e,fobj = pcall(fs.open,f,m)
|
|
|
|
if e and fobj then
|
|
|
|
local fdi, fdo =io.newfd()
|
|
|
|
if fobj.read then
|
|
|
|
function fdo.read(d)
|
|
|
|
return fobj:read(d)
|
2019-01-08 02:02:39 -05:00
|
|
|
end
|
2019-01-09 00:15:31 -05:00
|
|
|
elseif fobj.write then
|
|
|
|
function fdo.write(d)
|
|
|
|
return fobj:write(d)
|
2019-01-08 02:02:39 -05:00
|
|
|
end
|
|
|
|
end
|
2019-01-09 00:15:31 -05:00
|
|
|
function fdo.close()
|
|
|
|
fobj:close()
|
|
|
|
end
|
|
|
|
return fdi
|
2019-01-08 02:02:39 -05:00
|
|
|
end
|
2019-01-09 00:15:31 -05:00
|
|
|
return false
|
|
|
|
end
|
|
|
|
function io.open(f,m) -- opens file or file descriptor *f* with mode *m*
|
|
|
|
if type(f) == "string" then
|
|
|
|
f = fdfile(f,m)
|
2019-01-08 02:02:39 -05:00
|
|
|
end
|
2019-01-09 00:15:31 -05:00
|
|
|
if fd[f] then
|
|
|
|
local t = {["close"]=fdc,["read"]=fdr,["write"]=fdw,["fd"]=f,["mode"]=m}
|
|
|
|
return t
|
2019-01-08 02:02:39 -05:00
|
|
|
end
|
2019-01-09 00:15:31 -05:00
|
|
|
return false
|
2018-11-02 12:05:41 -04:00
|
|
|
end
|
|
|
|
end
|