summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-10-11 17:40:32 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-10-11 17:40:32 -0300
commit669129a6d8210e758ba94ea2786a370946572f7d (patch)
tree0d2734179612734956691caece1de19eeb352761
parent46b063ef59c7b334f8f36a9ab5dfd76d094e70d7 (diff)
downloadlua-669129a6d8210e758ba94ea2786a370946572f7d.tar.gz
lua-669129a6d8210e758ba94ea2786a370946572f7d.tar.bz2
lua-669129a6d8210e758ba94ea2786a370946572f7d.zip
io.lines() iterate over the standard input file
-rw-r--r--liolib.c35
1 files changed, 23 insertions, 12 deletions
diff --git a/liolib.c b/liolib.c
index d0799122..13d63d33 100644
--- a/liolib.c
+++ b/liolib.c
@@ -1,5 +1,5 @@
1/* 1/*
2** $Id: liolib.c,v 2.18 2002/09/17 20:35:54 roberto Exp roberto $ 2** $Id: liolib.c,v 2.19 2002/09/19 20:12:47 roberto Exp roberto $
3** Standard I/O (and system) library 3** Standard I/O (and system) library
4** See Copyright Notice in lua.h 4** See Copyright Notice in lua.h
5*/ 5*/
@@ -194,28 +194,39 @@ static int io_output (lua_State *L) {
194 194
195static int io_readline (lua_State *L); 195static int io_readline (lua_State *L);
196 196
197static int io_lines (lua_State *L) { 197
198 FILE *f = fopen(luaL_check_string(L, 1), "r"); 198static void aux_lines (lua_State *L, int index, int close) {
199 luaL_arg_check(L, f, 1, strerror(errno));
200 lua_pushliteral(L, FILEHANDLE); 199 lua_pushliteral(L, FILEHANDLE);
201 lua_rawget(L, LUA_REGISTRYINDEX); 200 lua_rawget(L, LUA_REGISTRYINDEX);
202 newfile(L, f); 201 lua_pushvalue(L, index);
203 lua_pushboolean(L, 1); /* must close file when finished */ 202 lua_pushboolean(L, close); /* close/not close file when finished */
204 lua_pushcclosure(L, io_readline, 3); 203 lua_pushcclosure(L, io_readline, 3);
205 return 1;
206} 204}
207 205
206
208static int f_lines (lua_State *L) { 207static int f_lines (lua_State *L) {
209 tofile(L, 1); /* check that it's a valid file handle */ 208 tofile(L, 1); /* check that it's a valid file handle */
210 lua_pushliteral(L, FILEHANDLE); 209 aux_lines(L, 1, 0);
211 lua_rawget(L, LUA_REGISTRYINDEX);
212 lua_pushvalue(L, 1);
213 lua_pushboolean(L, 0); /* does not close file when finished */
214 lua_pushcclosure(L, io_readline, 3);
215 return 1; 210 return 1;
216} 211}
217 212
218 213
214static int io_lines (lua_State *L) {
215 if (lua_isnoneornil(L, 1)) { /* no arguments? */
216 lua_pushstring(L, IO_INPUT);
217 lua_rawget(L, lua_upvalueindex(1)); /* will iterate over default input */
218 return f_lines(L);
219 }
220 else {
221 FILE *f = fopen(luaL_check_string(L, 1), "r");
222 luaL_arg_check(L, f, 1, strerror(errno));
223 newfile(L, f);
224 aux_lines(L, lua_gettop(L), 1);
225 return 1;
226 }
227}
228
229
219/* 230/*
220** {====================================================== 231** {======================================================
221** READ 232** READ