'io.read' accepts multiple formats in a single string argument

This commit is contained in:
Roberto Ierusalimschy 2017-11-16 14:28:36 -02:00
parent e4e5aa85a2
commit c47111bd4e
1 changed files with 31 additions and 27 deletions

View File

@ -1,5 +1,5 @@
/* /*
** $Id: liolib.c,v 2.152 2017/02/09 14:50:05 roberto Exp roberto $ ** $Id: liolib.c,v 2.153 2017/11/16 13:19:06 roberto Exp roberto $
** Standard I/O (and system) library ** Standard I/O (and system) library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@ -528,40 +528,44 @@ static int read_chars (lua_State *L, FILE *f, size_t n) {
static int g_read (lua_State *L, FILE *f, int first) { static int g_read (lua_State *L, FILE *f, int first) {
int nargs = lua_gettop(L) - 1; int nargs = lua_gettop(L) - 1;
int success; int nresults, success;
int n;
clearerr(f); clearerr(f);
if (nargs == 0) { /* no arguments? */ if (nargs == 0) { /* no arguments? */
success = read_line(L, f, 1); success = read_line(L, f, 1);
n = first+1; /* to return 1 result */ nresults = 1;
} }
else { /* ensure stack space for all results and for auxlib's buffer */ else {
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
success = 1; success = 1;
for (n = first; nargs-- && success; n++) { nresults = 0;
if (lua_type(L, n) == LUA_TNUMBER) { for (; nargs-- && success; first++) {
size_t l = (size_t)luaL_checkinteger(L, n); luaL_checkstack(L, LUA_MINSTACK, "too many arguments");
if (lua_type(L, first) == LUA_TNUMBER) {
size_t l = (size_t)luaL_checkinteger(L, first);
success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
nresults++;
} }
else { else {
const char *p = luaL_checkstring(L, n); const char *p = luaL_checkstring(L, first);
if (*p == '*') p++; /* skip optional '*' (for compatibility) */ if (*p == '*') p++; /* skip optional '*' (for compatibility) */
switch (*p) { for (; success && *p != '\0'; p++) {
case 'n': /* number */ nresults++;
success = read_number(L, f); switch (*p) {
break; case 'n': /* number */
case 'l': /* line */ success = read_number(L, f);
success = read_line(L, f, 1); break;
break; case 'l': /* line */
case 'L': /* line with end-of-line */ success = read_line(L, f, 1);
success = read_line(L, f, 0); break;
break; case 'L': /* line with end-of-line */
case 'a': /* file */ success = read_line(L, f, 0);
read_all(L, f); /* read entire file */ break;
success = 1; /* always success */ case 'a': /* file */
break; read_all(L, f); /* read entire file */
default: success = 1; /* always success */
return luaL_argerror(L, n, "invalid format"); break;
default:
return luaL_argerror(L, first, "invalid format");
}
} }
} }
} }
@ -572,7 +576,7 @@ static int g_read (lua_State *L, FILE *f, int first) {
lua_pop(L, 1); /* remove last result */ lua_pop(L, 1); /* remove last result */
lua_pushnil(L); /* push nil instead */ lua_pushnil(L); /* push nil instead */
} }
return n - first; return nresults;
} }