From 5525f63f02352a3347911d0d179657983ea5171a Mon Sep 17 00:00:00 2001 From: daurnimator Date: Thu, 27 Apr 2017 03:02:41 +1000 Subject: src/liolib: Add file:write() --- README.md | 2 +- src/liolib.js | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 804136a..d62d8d4 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ - [ ] `file:read()` - [ ] `file:read()` - [ ] `file:setvbuf()` - - [ ] `file:write()` + - [x] `file:write()` - [ ] `file:__gc()` - [x] `file:__tostring()` - [ ] C API diff --git a/src/liolib.js b/src/liolib.js index f581323..9940583 100644 --- a/src/liolib.js +++ b/src/liolib.js @@ -1,5 +1,6 @@ "use strict"; +const assert = require('assert'); const fs = require('fs'); const lua = require('./lua.js'); @@ -27,6 +28,14 @@ const f_tostring = function(L) { return 1; }; +const tofile = function(L) { + let p = tolstream(L); + if (isclosed(p)) + lauxlib.luaL_error(L, "attempt to use a closed file"); + assert(p.f); + return p.f; +}; + const newprefile = function(L) { let p = lua.lua_newuserdata(L); p.f = null; @@ -64,11 +73,18 @@ const io_write = function(L) { return g_write(L, getiofile(L, IO_OUTPUT), 1); }; +const f_write = function(L) { + let f = tofile(L); + lua.lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ + return g_write(L, f, 2); +}; + const iolib = { "write": io_write }; const flib = { + "write": f_write, "__tostring": f_tostring }; -- cgit v1.2.3-70-g09d2