static void io_write() { int32 arg = FIRSTARG; LuaFile *f = (LuaFile *)getfileparam(FOUTPUT, &arg); int32 status = 1; const char *s; while ((s = luaL_opt_string(arg++, NULL)) != NULL) status = status && ((int32)f->write(s, strlen(s)) != EOF); pushresult(status); }
static void io_read() { int32 arg = FIRSTARG; LuaFile *f = (LuaFile *)getfileparam(FINPUT, &arg); char *buff; const char *p = luaL_opt_string(arg, "[^\n]*{\n}"); int inskip = 0; // to control {skips} int c = NEED_OTHER; luaL_resetbuffer(); while (*p) { if (*p == '{') { inskip++; p++; } else if (*p == '}') { if (inskip == 0) lua_error("unbalanced braces in read pattern"); inskip--; p++; } else { const char *ep; // get what is next int m; // match result if (c == NEED_OTHER) { char z; if (f->read(&z, 1) != 1) c = EOF; else c = z; } m = luaI_singlematch((c == EOF) ? 0 : (char)c, p, &ep); if (m) { if (inskip == 0) luaL_addchar(c); c = NEED_OTHER; } switch (*ep) { case '*': // repetition if (!m) p = ep + 1; // else stay in (repeat) the same item break; case '?': // optional p = ep + 1; // continues reading the pattern break; default: if (m) p = ep; // continues reading the pattern else goto break_while; // pattern fails } } } break_while: if (c >= 0) // not EOF nor NEED_OTHER? f->seek(-1, SEEK_CUR); luaL_addchar(0); buff = luaL_buffer(); if (*buff != 0 || *p == 0) // read something or did not fail? lua_pushstring(buff); }
static void io_write (void) { int arg = FIRSTARG; FILE *f = getfileparam(FOUTPUT, &arg); int status = 1; char *s; while ((s = luaL_opt_string(arg++, NULL)) != NULL) status = status && (fputs(s, f) != EOF); pushresult(status); }
static void io_read (void) { int arg = FIRSTARG; FILE *f = getfileparam(FINPUT, &arg); char *buff; char *p = luaL_opt_string(arg, "[^\n]*{\n}"); int inskip = 0; /* to control {skips} */ int c = NEED_OTHER; luaL_resetbuffer(); while (*p) { if (*p == '{') { inskip++; p++; } else if (*p == '}') { if (inskip == 0) lua_error("unbalanced braces in read pattern"); inskip--; p++; } else { char *ep; /* get what is next */ int m; /* match result */ if (c == NEED_OTHER) c = getc(f); m = luaI_singlematch((c == EOF) ? 0 : (char)c, p, &ep); if (m) { if (inskip == 0) luaL_addchar(c); c = NEED_OTHER; } switch (*ep) { case '*': /* repetition */ if (!m) p = ep+1; /* else stay in (repeat) the same item */ break; case '?': /* optional */ p = ep+1; /* continues reading the pattern */ break; default: if (m) p = ep; /* continues reading the pattern */ else goto break_while; /* pattern fails */ } } } break_while: if (c >= 0) /* not EOF nor NEED_OTHER? */ ungetc(c, f); luaL_addchar(0); buff = luaL_buffer(); if (*buff != 0 || *p == 0) /* read something or did not fail? */ lua_pushstring(buff); }