summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordaurnimator <quae@daurnimator.com>2017-04-27 00:03:08 +1000
committerdaurnimator <quae@daurnimator.com>2017-05-03 18:28:24 +1000
commit290ddad546117d6b55639faa7ad943d96f8e224c (patch)
treecb3c95a8a6b1e7b7efa3e73d3cc67f04ad834243
parent9a24308b0f8bb04d533d9abae39bd7546cf92377 (diff)
downloadfengari-290ddad546117d6b55639faa7ad943d96f8e224c.tar.gz
fengari-290ddad546117d6b55639faa7ad943d96f8e224c.tar.bz2
fengari-290ddad546117d6b55639faa7ad943d96f8e224c.zip
src/liolib.js: Implement io.write
-rw-r--r--README.md2
-rw-r--r--src/liolib.js32
2 files changed, 33 insertions, 1 deletions
diff --git a/README.md b/README.md
index 02110dd..804136a 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@
- [ ] `io.read()`
- [ ] `io.tmpfile()`
- [ ] `io.type()`
- - [ ] `io.write()`
+ - [x] `io.write()`
- [ ] `io.close()`
- [ ] `file:flush()`
- [ ] `file:lines()`
diff --git a/src/liolib.js b/src/liolib.js
index f753f91..f581323 100644
--- a/src/liolib.js
+++ b/src/liolib.js
@@ -1,5 +1,7 @@
"use strict";
+const fs = require('fs');
+
const lua = require('./lua.js');
const lauxlib = require('./lauxlib.js');
@@ -33,7 +35,37 @@ const newprefile = function(L) {
return p;
};
+const getiofile = function(L, findex) {
+ lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, findex);
+ let p = lua.lua_touserdata(L, -1);
+ if (isclosed(p))
+ lauxlib.luaL_error(L, lua.to_luastring(`standard ${lua.to_jsstring(findex.slice(IOPREF_LEN))} file is closed`));
+ return p.f;
+};
+
+const g_write = function(L, f, arg) {
+ let nargs = lua.lua_gettop(L) - arg;
+ let status = true;
+ let err;
+ for (; nargs--; arg++) {
+ let s = lauxlib.luaL_checklstring(L, arg);
+ try {
+ status = status && (fs.writeSync(f.fd, Uint8Array.from(s)) === s.length);
+ } catch (e) {
+ status = false;
+ err = e;
+ }
+ }
+ if (status) return 1; /* file handle already on stack top */
+ else return lauxlib.luaL_fileresult(L, status, null, err);
+};
+
+const io_write = function(L) {
+ return g_write(L, getiofile(L, IO_OUTPUT), 1);
+};
+
const iolib = {
+ "write": io_write
};
const flib = {