2 ** $Id: liolib.c,v 1.91 2000/10/31 13:10:24 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
24 #define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
25 #define free(b) if (b) (free)(b)
27 /* no support for locale and for strerror: fake them */
28 #define setlocale(a,b) ((void)a, strcmp((b),"C")==0?"C":NULL)
35 #define strerror(e) "generic I/O error"
44 #define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
46 /* no support for popen */
47 #define popen(x,y) NULL /* that is, popen always fails */
48 #define CLOSEFILE(L, f) (fclose(f))
55 typedef struct IOCtrl
{
56 int ref
[2]; /* ref for strings _INPUT/_OUTPUT */
57 int iotag
; /* tag for file handles */
58 int closedtag
; /* tag for closed handles */
63 static const char *const filenames
[] = {"_INPUT", "_OUTPUT"};
66 static int pushresult (lua_State
*L
, int i
) {
68 lua_pushuserdata(L
, NULL
);
73 lua_pushstring(L
, strerror(errno
));
74 lua_pushnumber(L
, errno
);
81 ** {======================================================
83 ** =======================================================
87 static FILE *gethandle (lua_State
*L
, IOCtrl
*ctrl
, int f
) {
88 void *p
= lua_touserdata(L
, f
);
89 if (p
!= NULL
) { /* is `f' a userdata ? */
90 int ftag
= lua_tag(L
, f
);
91 if (ftag
== ctrl
->iotag
) /* does it have the correct tag? */
93 else if (ftag
== ctrl
->closedtag
)
94 lua_error(L
, "cannot access a closed file");
101 static FILE *getnonullfile (lua_State
*L
, IOCtrl
*ctrl
, int arg
) {
102 FILE *f
= gethandle(L
, ctrl
, arg
);
103 luaL_arg_check(L
, f
, arg
, "invalid file handle");
108 static FILE *getfilebyref (lua_State
*L
, IOCtrl
*ctrl
, int inout
) {
111 lua_getref(L
, ctrl
->ref
[inout
]);
113 f
= gethandle(L
, ctrl
, -1);
115 luaL_verror(L
, "global variable `%.10s' is not a file handle",
121 static void setfilebyname (lua_State
*L
, IOCtrl
*ctrl
, FILE *f
,
123 lua_pushusertag(L
, f
, ctrl
->iotag
);
124 lua_setglobal(L
, name
);
128 #define setfile(L,ctrl,f,inout) (setfilebyname(L,ctrl,f,filenames[inout]))
131 static int setreturn (lua_State
*L
, IOCtrl
*ctrl
, FILE *f
, int inout
) {
133 return pushresult(L
, 0);
135 setfile(L
, ctrl
, f
, inout
);
136 lua_pushusertag(L
, f
, ctrl
->iotag
);
142 static int closefile (lua_State
*L
, IOCtrl
*ctrl
, FILE *f
) {
143 if (f
== stdin
|| f
== stdout
|| f
== stderr
)
146 lua_pushusertag(L
, f
, ctrl
->iotag
);
147 lua_settag(L
, ctrl
->closedtag
);
148 return (CLOSEFILE(L
, f
) == 0);
153 static int io_close (lua_State
*L
) {
154 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
155 lua_pop(L
, 1); /* remove upvalue */
156 return pushresult(L
, closefile(L
, ctrl
, getnonullfile(L
, ctrl
, 1)));
160 static int file_collect (lua_State
*L
) {
161 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
162 FILE *f
= getnonullfile(L
, ctrl
, 1);
163 if (f
!= stdin
&& f
!= stdout
&& f
!= stderr
)
169 static int io_open (lua_State
*L
) {
170 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
172 lua_pop(L
, 1); /* remove upvalue */
173 f
= fopen(luaL_check_string(L
, 1), luaL_check_string(L
, 2));
175 lua_pushusertag(L
, f
, ctrl
->iotag
);
179 return pushresult(L
, 0);
184 static int io_fromto (lua_State
*L
, int inout
, const char *mode
) {
185 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
187 lua_pop(L
, 1); /* remove upvalue */
188 if (lua_isnull(L
, 1)) {
189 closefile(L
, ctrl
, getfilebyref(L
, ctrl
, inout
));
190 current
= (inout
== 0) ? stdin
: stdout
;
192 else if (lua_tag(L
, 1) == ctrl
->iotag
) /* deprecated option */
193 current
= (FILE *)lua_touserdata(L
, 1);
195 const char *s
= luaL_check_string(L
, 1);
196 current
= (*s
== '|') ? popen(s
+1, mode
) : fopen(s
, mode
);
198 return setreturn(L
, ctrl
, current
, inout
);
202 static int io_readfrom (lua_State
*L
) {
203 return io_fromto(L
, INFILE
, "r");
207 static int io_writeto (lua_State
*L
) {
208 return io_fromto(L
, OUTFILE
, "w");
212 static int io_appendto (lua_State
*L
) {
213 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
215 lua_pop(L
, 1); /* remove upvalue */
216 current
= fopen(luaL_check_string(L
, 1), "a");
217 return setreturn(L
, ctrl
, current
, OUTFILE
);
223 ** {======================================================
225 ** =======================================================
230 #ifdef LUA_COMPAT_READPATTERN
233 ** We cannot lookahead without need, because this can lock stdin.
234 ** This flag signals when we need to read a next char.
236 #define NEED_OTHER (EOF-1) /* just some flag different from EOF */
239 static int read_pattern (lua_State
*L
, FILE *f
, const char *p
) {
240 int inskip
= 0; /* {skip} level */
243 luaL_buffinit(L
, &b
);
251 if (!inskip
) lua_error(L
, "unbalanced braces in read pattern");
256 const char *ep
= luaI_classend(L
, p
); /* get what is next */
257 int m
; /* match result */
258 if (c
== NEED_OTHER
) c
= getc(f
);
259 m
= (c
==EOF
) ? 0 : luaI_singlematch(c
, p
, ep
);
261 if (!inskip
) luaL_putchar(&b
, c
);
265 case '+': /* repetition (1 or more) */
266 if (!m
) goto break_while
; /* pattern fails? */
267 /* else go through */
268 case '*': /* repetition (0 or more) */
269 while (m
) { /* reads the same item until it fails */
271 m
= (c
==EOF
) ? 0 : luaI_singlematch(c
, p
, ep
);
272 if (m
&& !inskip
) luaL_putchar(&b
, c
);
274 /* go through to continue reading the pattern */
275 case '?': /* optional */
276 p
= ep
+1; /* continues reading the pattern */
279 if (!m
) goto break_while
; /* pattern fails? */
280 p
= ep
; /* else continues reading the pattern */
285 if (c
!= NEED_OTHER
) ungetc(c
, f
);
286 luaL_pushresult(&b
); /* close buffer */
292 #define read_pattern(L, f, p) (lua_error(L, "read patterns are deprecated"), 0)
297 static int read_number (lua_State
*L
, FILE *f
) {
299 if (fscanf(f
, "%lf", &d
) == 1) {
300 lua_pushnumber(L
, d
);
303 else return 0; /* read fails */
307 static int read_word (lua_State
*L
, FILE *f
) {
310 luaL_buffinit(L
, &b
);
311 do { c
= fgetc(f
); } while (isspace(c
)); /* skip spaces */
312 while (c
!= EOF
&& !isspace(c
)) {
317 luaL_pushresult(&b
); /* close buffer */
318 return (lua_strlen(L
, -1) > 0);
322 static int read_line (lua_State
*L
, FILE *f
) {
325 luaL_buffinit(L
, &b
);
327 char *p
= luaL_prepbuffer(&b
);
328 if (!fgets(p
, LUAL_BUFFERSIZE
, f
)) /* read fails? */
334 luaL_addsize(&b
, n
-1); /* do not add the `\n' */
338 luaL_pushresult(&b
); /* close buffer */
339 return (n
> 0); /* read something? */
343 static void read_file (lua_State
*L
, FILE *f
) {
345 size_t size
= BUFSIZ
;
348 char *newbuffer
= (char *)realloc(buffer
, size
);
349 if (newbuffer
== NULL
) {
351 lua_error(L
, "not enough memory to read a file");
354 len
+= fread(buffer
+len
, sizeof(char), size
-len
, f
);
355 if (len
< size
) break; /* did not read all it could */
358 lua_pushlstring(L
, buffer
, len
);
363 static int read_chars (lua_State
*L
, FILE *f
, size_t n
) {
366 char statbuff
[BUFSIZ
];
370 buffer
= (char *)malloc(n
);
372 lua_error(L
, "not enough memory to read a file");
374 n1
= fread(buffer
, sizeof(char), n
, f
);
375 lua_pushlstring(L
, buffer
, n1
);
376 if (buffer
!= statbuff
) free(buffer
);
377 return (n1
> 0 || n
== 0);
381 static int io_read (lua_State
*L
) {
382 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
383 int lastarg
= lua_gettop(L
) - 1;
385 FILE *f
= gethandle(L
, ctrl
, firstarg
);
388 else f
= getfilebyref(L
, ctrl
, INFILE
); /* get _INPUT */
390 if (firstarg
> lastarg
) { /* no arguments? */
391 lua_settop(L
, 0); /* erase upvalue and other eventual garbage */
392 firstarg
= lastarg
= 1; /* correct indices */
393 lua_pushstring(L
, "*l"); /* push default argument */
395 else /* ensure stack space for all results and for auxlib's buffer */
396 luaL_checkstack(L
, lastarg
-firstarg
+1+LUA_MINSTACK
, "too many arguments");
397 for (n
= firstarg
; n
<=lastarg
; n
++) {
399 if (lua_isnumber(L
, n
))
400 success
= read_chars(L
, f
, (size_t)lua_tonumber(L
, n
));
402 const char *p
= luaL_check_string(L
, n
);
404 success
= read_pattern(L
, f
, p
); /* deprecated! */
407 case 'n': /* number */
408 if (!read_number(L
, f
)) goto endloop
; /* read fails */
409 continue; /* number is already pushed; avoid the "pushstring" */
411 success
= read_line(L
, f
);
415 success
= 1; /* always success */
418 success
= read_word(L
, f
);
421 luaL_argerror(L
, n
, "invalid format");
422 success
= 0; /* to avoid warnings */
427 lua_pop(L
, 1); /* remove last result */
428 break; /* read fails */
434 /* }====================================================== */
437 static int io_write (lua_State
*L
) {
438 int lastarg
= lua_gettop(L
) - 1;
439 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
442 FILE *f
= gethandle(L
, ctrl
, arg
);
444 else f
= getfilebyref(L
, ctrl
, OUTFILE
); /* get _OUTPUT */
445 for (; arg
<= lastarg
; arg
++) {
446 if (lua_type(L
, arg
) == LUA_TNUMBER
) { /* LUA_NUMBER */
447 /* optimization: could be done exactly as for strings */
448 status
= status
&& fprintf(f
, "%.16g", lua_tonumber(L
, arg
)) > 0;
452 const char *s
= luaL_check_lstr(L
, arg
, &l
);
453 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
456 pushresult(L
, status
);
461 static int io_seek (lua_State
*L
) {
462 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
463 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
464 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
468 lua_pop(L
, 1); /* remove upvalue */
469 f
= getnonullfile(L
, ctrl
, 1);
470 op
= luaL_findstring(luaL_opt_string(L
, 2, "cur"), modenames
);
471 offset
= luaL_opt_long(L
, 3, 0);
472 luaL_arg_check(L
, op
!= -1, 2, "invalid mode");
473 op
= fseek(f
, offset
, mode
[op
]);
475 return pushresult(L
, 0); /* error */
477 lua_pushnumber(L
, ftell(f
));
483 static int io_flush (lua_State
*L
) {
484 IOCtrl
*ctrl
= (IOCtrl
*)lua_touserdata(L
, -1);
486 lua_pop(L
, 1); /* remove upvalue */
487 f
= gethandle(L
, ctrl
, 1);
488 luaL_arg_check(L
, f
|| lua_isnull(L
, 1), 1, "invalid file handle");
489 return pushresult(L
, fflush(f
) == 0);
492 /* }====================================================== */
496 ** {======================================================
497 ** Other O.S. Operations
498 ** =======================================================
501 static int io_execute (lua_State
*L
) {
502 lua_pushnumber(L
, system(luaL_check_string(L
, 1)));
507 static int io_remove (lua_State
*L
) {
508 return pushresult(L
, remove(luaL_check_string(L
, 1)) == 0);
512 static int io_rename (lua_State
*L
) {
513 return pushresult(L
, rename(luaL_check_string(L
, 1),
514 luaL_check_string(L
, 2)) == 0);
518 static int io_tmpname (lua_State
*L
) {
519 lua_pushstring(L
, tmpnam(NULL
));
525 static int io_getenv (lua_State
*L
) {
526 lua_pushstring(L
, getenv(luaL_check_string(L
, 1))); /* if NULL push nil */
531 static int io_clock (lua_State
*L
) {
532 lua_pushnumber(L
, ((double)clock())/CLOCKS_PER_SEC
);
537 static int io_date (lua_State
*L
) {
539 const char *s
= luaL_opt_string(L
, 1, "%c");
542 time(&t
); stm
= localtime(&t
);
543 if (strftime(b
, sizeof(b
), s
, stm
))
544 lua_pushstring(L
, b
);
546 lua_error(L
, "invalid `date' format");
551 static int setloc (lua_State
*L
) {
552 static const int cat
[] = {LC_ALL
, LC_COLLATE
, LC_CTYPE
, LC_MONETARY
,
553 LC_NUMERIC
, LC_TIME
};
554 static const char *const catnames
[] = {"all", "collate", "ctype", "monetary",
555 "numeric", "time", NULL
};
556 int op
= luaL_findstring(luaL_opt_string(L
, 2, "all"), catnames
);
557 luaL_arg_check(L
, op
!= -1, 2, "invalid option");
558 lua_pushstring(L
, setlocale(cat
[op
], luaL_check_string(L
, 1)));
563 static int io_exit (lua_State
*L
) {
564 exit(luaL_opt_int(L
, 1, EXIT_SUCCESS
));
565 return 0; /* to avoid warnings */
568 /* }====================================================== */
572 static int io_debug (lua_State
*L
) {
575 fprintf(stderr
, "lua_debug> ");
576 if (fgets(buffer
, sizeof(buffer
), stdin
) == 0 ||
577 strcmp(buffer
, "cont\n") == 0)
579 lua_dostring(L
, buffer
);
580 lua_settop(L
, 0); /* remove eventual returns */
585 #define LEVELS1 12 /* size of the first part of the stack */
586 #define LEVELS2 10 /* size of the second part of the stack */
588 static int errorfb (lua_State
*L
) {
589 int level
= 1; /* skip level 0 (it's this function) */
590 int firstpart
= 1; /* still before eventual `...' */
593 luaL_buffinit(L
, &b
);
594 luaL_addstring(&b
, "error: ");
595 luaL_addstring(&b
, luaL_check_string(L
, 1));
596 luaL_addstring(&b
, "\n");
597 while (lua_getstack(L
, level
++, &ar
)) {
598 char buff
[120]; /* enough to fit following `sprintf's */
600 luaL_addstring(&b
, "stack traceback:\n");
601 else if (level
> LEVELS1
&& firstpart
) {
602 /* no more than `LEVELS2' more levels? */
603 if (!lua_getstack(L
, level
+LEVELS2
, &ar
))
604 level
--; /* keep going */
606 luaL_addstring(&b
, " ...\n"); /* too many levels */
607 while (lua_getstack(L
, level
+LEVELS2
, &ar
)) /* find last levels */
613 sprintf(buff
, "%4d: ", level
-1);
614 luaL_addstring(&b
, buff
);
615 lua_getinfo(L
, "Snl", &ar
);
616 switch (*ar
.namewhat
) {
617 case 'g': case 'l': /* global, local */
618 sprintf(buff
, "function `%.50s'", ar
.name
);
620 case 'f': /* field */
621 sprintf(buff
, "method `%.50s'", ar
.name
);
623 case 't': /* tag method */
624 sprintf(buff
, "`%.50s' tag method", ar
.name
);
627 if (*ar
.what
== 'm') /* main? */
628 sprintf(buff
, "main of %.70s", ar
.short_src
);
629 else if (*ar
.what
== 'C') /* C function? */
630 sprintf(buff
, "%.70s", ar
.short_src
);
632 sprintf(buff
, "function <%d:%.70s>", ar
.linedefined
, ar
.short_src
);
633 ar
.source
= NULL
; /* do not print source again */
636 luaL_addstring(&b
, buff
);
637 if (ar
.currentline
> 0) {
638 sprintf(buff
, " at line %d", ar
.currentline
);
639 luaL_addstring(&b
, buff
);
642 sprintf(buff
, " [%.70s]", ar
.short_src
);
643 luaL_addstring(&b
, buff
);
645 luaL_addstring(&b
, "\n");
648 lua_getglobal(L
, LUA_ALERT
);
649 if (lua_isfunction(L
, -1)) { /* avoid loop if _ALERT is not defined */
650 lua_pushvalue(L
, -2); /* error message */
651 lua_rawcall(L
, 1, 0);
658 static const struct luaL_reg iolib
[] = {
659 {LUA_ERRORMESSAGE
, errorfb
},
663 {"execute", io_execute
},
665 {"getenv", io_getenv
},
666 {"remove", io_remove
},
667 {"rename", io_rename
},
668 {"setlocale", setloc
},
669 {"tmpname", io_tmpname
}
673 static const struct luaL_reg iolibtag
[] = {
674 {"appendto", io_appendto
},
675 {"closefile", io_close
},
677 {"openfile", io_open
},
679 {"readfrom", io_readfrom
},
682 {"writeto", io_writeto
}
686 static void openwithcontrol (lua_State
*L
) {
687 IOCtrl
*ctrl
= (IOCtrl
*)lua_newuserdata(L
, sizeof(IOCtrl
));
689 ctrl
->iotag
= lua_newtag(L
);
690 ctrl
->closedtag
= lua_newtag(L
);
691 for (i
=0; i
<sizeof(iolibtag
)/sizeof(iolibtag
[0]); i
++) {
692 /* put `ctrl' as upvalue for these functions */
693 lua_pushvalue(L
, -1);
694 lua_pushcclosure(L
, iolibtag
[i
].func
, 1);
695 lua_setglobal(L
, iolibtag
[i
].name
);
697 /* create references to variable names */
698 lua_pushstring(L
, filenames
[INFILE
]);
699 ctrl
->ref
[INFILE
] = lua_ref(L
, 1);
700 lua_pushstring(L
, filenames
[OUTFILE
]);
701 ctrl
->ref
[OUTFILE
] = lua_ref(L
, 1);
702 /* predefined file handles */
703 setfile(L
, ctrl
, stdin
, INFILE
);
704 setfile(L
, ctrl
, stdout
, OUTFILE
);
705 setfilebyname(L
, ctrl
, stdin
, "_STDIN");
706 setfilebyname(L
, ctrl
, stdout
, "_STDOUT");
707 setfilebyname(L
, ctrl
, stderr
, "_STDERR");
708 /* close files when collected */
709 lua_pushcclosure(L
, file_collect
, 1); /* pops `ctrl' from stack */
710 lua_settagmethod(L
, ctrl
->iotag
, "gc");
714 LUALIB_API
void lua_iolibopen (lua_State
*L
) {
715 luaL_openl(L
, iolib
);