From 56b5adb7f3683cd9e88f8d2cabd885e49a3d2398 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Wed, 26 Apr 2017 23:29:17 +1000 Subject: src/iolib.js: Create stdin/stdout/stderr --- README.md | 6 +++--- src/liolib.js | 40 ++++++++++++++++++++++++++++++++++++++++ 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; }; -- cgit v1.2.3-70-g09d2