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