aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordaurnimator <quae@daurnimator.com>2017-04-26 23:29:17 +1000
committerdaurnimator <quae@daurnimator.com>2017-05-03 18:27:15 +1000
commit56b5adb7f3683cd9e88f8d2cabd885e49a3d2398 (patch)
tree473901087179af752eb26a704b640599c98b9965
parentc3ea98864c5ee7535f40704b28229dbad676d2fb (diff)
downloadfengari-56b5adb7f3683cd9e88f8d2cabd885e49a3d2398.tar.gz
fengari-56b5adb7f3683cd9e88f8d2cabd885e49a3d2398.tar.bz2
fengari-56b5adb7f3683cd9e88f8d2cabd885e49a3d2398.zip
src/iolib.js: Create stdin/stdout/stderr
-rw-r--r--README.md6
-rw-r--r--src/liolib.js40
2 files changed, 43 insertions, 3 deletions
diff --git a/README.md b/README.md
index 9d7e70e..56f3496 100644
--- a/README.md
+++ b/README.md
@@ -25,9 +25,9 @@
- [x] os (~~`os.setlocale()`~~)
- [ ] Package
- [ ] io
- - [ ] `io.stdin`
- - [ ] `io.stdout`
- - [ ] `io.stderr`
+ - [x] `io.stdin`
+ - [x] `io.stdout`
+ - [x] `io.stderr`
- [ ] `io.flush()`
- [ ] `io.input()`
- [ ] `io.lines()`
diff --git a/src/liolib.js b/src/liolib.js
index 22dc2e8..247baef 100644
--- a/src/liolib.js
+++ b/src/liolib.js
@@ -3,6 +3,23 @@
const lua = require('./lua.js');
const lauxlib = require('./lauxlib.js');
+const IO_PREFIX = "_IO_";
+const IOPREF_LEN = IO_PREFIX.length;
+const IO_INPUT = lua.to_luastring(IO_PREFIX + "input");
+const IO_OUTPUT = lua.to_luastring(IO_PREFIX + "output");
+
+const tolstream = function(L) {
+ return lauxlib.luaL_checkudata(L, 1, lauxlib.LUA_FILEHANDLE);
+};
+
+const newprefile = function(L) {
+ let p = lua.lua_newuserdata(L);
+ p.f = null;
+ p.closef = null;
+ lauxlib.luaL_setmetatable(L, lauxlib.LUA_FILEHANDLE);
+ return p;
+};
+
const iolib = {
};
@@ -17,9 +34,32 @@ const createmeta = function(L) {
lua.lua_pop(L, 1); /* pop new metatable */
};
+const io_noclose = function(L) {
+ let p = tolstream(L);
+ p.closef = io_noclose;
+ lua.lua_pushnil(L);
+ lua.lua_pushliteral(L, "cannot close standard file");
+ return 2;
+};
+
+const createstdfile = function(L, f, k, fname) {
+ let p = newprefile(L);
+ p.f = f;
+ p.closef = io_noclose;
+ if (k !== null) {
+ lua.lua_pushvalue(L, -1);
+ lua.lua_setfield(L, lua.LUA_REGISTRYINDEX, k); /* add file to registry */
+ }
+ lua.lua_setfield(L, -2, fname); /* add file to module */
+};
+
const luaopen_io = function(L) {
lauxlib.luaL_newlib(L, iolib);
createmeta(L);
+ /* create (and set) default files */
+ createstdfile(L, process.stdin, IO_INPUT, lua.to_luastring("stdin"));
+ createstdfile(L, process.stdout, IO_OUTPUT, lua.to_luastring("stdout"));
+ createstdfile(L, process.stderr, null, lua.to_luastring("stderr"));
return 1;
};