xref: /netbsd-src/external/mit/lua/dist/src/lauxlib.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: lauxlib.c,v 1.6 2016/01/28 14:41:39 lneto Exp $	*/
2 
3 /*
4 ** Id: lauxlib.c,v 1.284 2015/11/19 19:16:22 roberto Exp
5 ** Auxiliary functions for building Lua libraries
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lauxlib_c
10 #define LUA_LIB
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <errno.h>
17 #endif /* _KERNEL */
18 #include <stdarg.h>
19 #ifndef _KERNEL
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #endif /* _KERNEL */
24 
25 
26 /* This file uses only the official API of Lua.
27 ** Any function declared here could be written as an application function.
28 */
29 
30 #include "lua.h"
31 
32 #include "lauxlib.h"
33 
34 
35 /*
36 ** {======================================================
37 ** Traceback
38 ** =======================================================
39 */
40 
41 
42 #define LEVELS1	10	/* size of the first part of the stack */
43 #define LEVELS2	11	/* size of the second part of the stack */
44 
45 
46 
47 /*
48 ** search for 'objidx' in table at index -1.
49 ** return 1 + string at top if find a good name.
50 */
51 static int findfield (lua_State *L, int objidx, int level) {
52   if (level == 0 || !lua_istable(L, -1))
53     return 0;  /* not found */
54   lua_pushnil(L);  /* start 'next' loop */
55   while (lua_next(L, -2)) {  /* for each pair in table */
56     if (lua_type(L, -2) == LUA_TSTRING) {  /* ignore non-string keys */
57       if (lua_rawequal(L, objidx, -1)) {  /* found object? */
58         lua_pop(L, 1);  /* remove value (but keep name) */
59         return 1;
60       }
61       else if (findfield(L, objidx, level - 1)) {  /* try recursively */
62         lua_remove(L, -2);  /* remove table (but keep name) */
63         lua_pushliteral(L, ".");
64         lua_insert(L, -2);  /* place '.' between the two names */
65         lua_concat(L, 3);
66         return 1;
67       }
68     }
69     lua_pop(L, 1);  /* remove value */
70   }
71   return 0;  /* not found */
72 }
73 
74 
75 /*
76 ** Search for a name for a function in all loaded modules
77 ** (registry._LOADED).
78 */
79 static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
80   int top = lua_gettop(L);
81   lua_getinfo(L, "f", ar);  /* push function */
82   lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
83   if (findfield(L, top + 1, 2)) {
84     const char *name = lua_tostring(L, -1);
85     if (strncmp(name, "_G.", 3) == 0) {  /* name start with '_G.'? */
86       lua_pushstring(L, name + 3);  /* push name without prefix */
87       lua_remove(L, -2);  /* remove original name */
88     }
89     lua_copy(L, -1, top + 1);  /* move name to proper place */
90     lua_pop(L, 2);  /* remove pushed values */
91     return 1;
92   }
93   else {
94     lua_settop(L, top);  /* remove function and global table */
95     return 0;
96   }
97 }
98 
99 
100 static void pushfuncname (lua_State *L, lua_Debug *ar) {
101   if (pushglobalfuncname(L, ar)) {  /* try first a global name */
102     lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
103     lua_remove(L, -2);  /* remove name */
104   }
105   else if (*ar->namewhat != '\0')  /* is there a name from code? */
106     lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name);  /* use it */
107   else if (*ar->what == 'm')  /* main? */
108       lua_pushliteral(L, "main chunk");
109   else if (*ar->what != 'C')  /* for Lua functions, use <file:line> */
110     lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
111   else  /* nothing left... */
112     lua_pushliteral(L, "?");
113 }
114 
115 
116 static int lastlevel (lua_State *L) {
117   lua_Debug ar;
118   int li = 1, le = 1;
119   /* find an upper bound */
120   while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
121   /* do a binary search */
122   while (li < le) {
123     int m = (li + le)/2;
124     if (lua_getstack(L, m, &ar)) li = m + 1;
125     else le = m;
126   }
127   return le - 1;
128 }
129 
130 
131 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
132                                 const char *msg, int level) {
133   lua_Debug ar;
134   int top = lua_gettop(L);
135   int last = lastlevel(L1);
136   int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
137   if (msg)
138     lua_pushfstring(L, "%s\n", msg);
139   luaL_checkstack(L, 10, NULL);
140   lua_pushliteral(L, "stack traceback:");
141   while (lua_getstack(L1, level++, &ar)) {
142     if (n1-- == 0) {  /* too many levels? */
143       lua_pushliteral(L, "\n\t...");  /* add a '...' */
144       level = last - LEVELS2 + 1;  /* and skip to last ones */
145     }
146     else {
147       lua_getinfo(L1, "Slnt", &ar);
148       lua_pushfstring(L, "\n\t%s:", ar.short_src);
149       if (ar.currentline > 0)
150         lua_pushfstring(L, "%d:", ar.currentline);
151       lua_pushliteral(L, " in ");
152       pushfuncname(L, &ar);
153       if (ar.istailcall)
154         lua_pushliteral(L, "\n\t(...tail calls...)");
155       lua_concat(L, lua_gettop(L) - top);
156     }
157   }
158   lua_concat(L, lua_gettop(L) - top);
159 }
160 
161 /* }====================================================== */
162 
163 
164 /*
165 ** {======================================================
166 ** Error-report functions
167 ** =======================================================
168 */
169 
170 LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
171   lua_Debug ar;
172   if (!lua_getstack(L, 0, &ar))  /* no stack frame? */
173     return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
174   lua_getinfo(L, "n", &ar);
175   if (strcmp(ar.namewhat, "method") == 0) {
176     arg--;  /* do not count 'self' */
177     if (arg == 0)  /* error is in the self argument itself? */
178       return luaL_error(L, "calling '%s' on bad self (%s)",
179                            ar.name, extramsg);
180   }
181   if (ar.name == NULL)
182     ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
183   return luaL_error(L, "bad argument #%d to '%s' (%s)",
184                         arg, ar.name, extramsg);
185 }
186 
187 
188 static int typeerror (lua_State *L, int arg, const char *tname) {
189   const char *msg;
190   const char *typearg;  /* name for the type of the actual argument */
191   if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
192     typearg = lua_tostring(L, -1);  /* use the given type name */
193   else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
194     typearg = "light userdata";  /* special name for messages */
195   else
196     typearg = luaL_typename(L, arg);  /* standard name */
197   msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
198   return luaL_argerror(L, arg, msg);
199 }
200 
201 
202 static void tag_error (lua_State *L, int arg, int tag) {
203   typeerror(L, arg, lua_typename(L, tag));
204 }
205 
206 
207 LUALIB_API void luaL_where (lua_State *L, int level) {
208   lua_Debug ar;
209   if (lua_getstack(L, level, &ar)) {  /* check function at level */
210     lua_getinfo(L, "Sl", &ar);  /* get info about it */
211     if (ar.currentline > 0) {  /* is there info? */
212       lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
213       return;
214     }
215   }
216   lua_pushliteral(L, "");  /* else, no information available... */
217 }
218 
219 
220 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
221   va_list argp;
222   va_start(argp, fmt);
223   luaL_where(L, 1);
224   lua_pushvfstring(L, fmt, argp);
225   va_end(argp);
226   lua_concat(L, 2);
227   return lua_error(L);
228 }
229 
230 
231 #ifndef _KERNEL
232 LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
233   int en = errno;  /* calls to Lua API may change this value */
234   if (stat) {
235     lua_pushboolean(L, 1);
236     return 1;
237   }
238   else {
239     lua_pushnil(L);
240     if (fname)
241       lua_pushfstring(L, "%s: %s", fname, strerror(en));
242     else
243       lua_pushstring(L, strerror(en));
244     lua_pushinteger(L, en);
245     return 3;
246   }
247 }
248 #endif /* _KERNEL */
249 
250 
251 #if !defined(l_inspectstat)	/* { */
252 
253 #if defined(LUA_USE_POSIX)
254 
255 #include <sys/wait.h>
256 
257 /*
258 ** use appropriate macros to interpret 'pclose' return status
259 */
260 #define l_inspectstat(stat,what)  \
261    if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
262    else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
263 
264 #else
265 
266 #define l_inspectstat(stat,what)  /* no op */
267 
268 #endif
269 
270 #endif				/* } */
271 
272 
273 #ifndef _KERNEL
274 LUALIB_API int luaL_execresult (lua_State *L, int stat) {
275   const char *what = "exit";  /* type of termination */
276   if (stat == -1)  /* error? */
277     return luaL_fileresult(L, 0, NULL);
278   else {
279     l_inspectstat(stat, what);  /* interpret result */
280     if (*what == 'e' && stat == 0)  /* successful termination? */
281       lua_pushboolean(L, 1);
282     else
283       lua_pushnil(L);
284     lua_pushstring(L, what);
285     lua_pushinteger(L, stat);
286     return 3;  /* return true/nil,what,code */
287   }
288 }
289 #endif /* _KERNEL */
290 
291 /* }====================================================== */
292 
293 
294 /*
295 ** {======================================================
296 ** Userdata's metatable manipulation
297 ** =======================================================
298 */
299 
300 LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
301   if (luaL_getmetatable(L, tname) != LUA_TNIL)  /* name already in use? */
302     return 0;  /* leave previous value on top, but return 0 */
303   lua_pop(L, 1);
304   lua_createtable(L, 0, 2);  /* create metatable */
305   lua_pushstring(L, tname);
306   lua_setfield(L, -2, "__name");  /* metatable.__name = tname */
307   lua_pushvalue(L, -1);
308   lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
309   return 1;
310 }
311 
312 
313 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
314   luaL_getmetatable(L, tname);
315   lua_setmetatable(L, -2);
316 }
317 
318 
319 LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
320   void *p = lua_touserdata(L, ud);
321   if (p != NULL) {  /* value is a userdata? */
322     if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */
323       luaL_getmetatable(L, tname);  /* get correct metatable */
324       if (!lua_rawequal(L, -1, -2))  /* not the same? */
325         p = NULL;  /* value is a userdata with wrong metatable */
326       lua_pop(L, 2);  /* remove both metatables */
327       return p;
328     }
329   }
330   return NULL;  /* value is not a userdata with a metatable */
331 }
332 
333 
334 LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
335   void *p = luaL_testudata(L, ud, tname);
336   if (p == NULL) typeerror(L, ud, tname);
337   return p;
338 }
339 
340 /* }====================================================== */
341 
342 
343 /*
344 ** {======================================================
345 ** Argument check functions
346 ** =======================================================
347 */
348 
349 LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
350                                  const char *const lst[]) {
351   const char *name = (def) ? luaL_optstring(L, arg, def) :
352                              luaL_checkstring(L, arg);
353   int i;
354   for (i=0; lst[i]; i++)
355     if (strcmp(lst[i], name) == 0)
356       return i;
357   return luaL_argerror(L, arg,
358                        lua_pushfstring(L, "invalid option '%s'", name));
359 }
360 
361 
362 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
363   /* keep some extra space to run error routines, if needed */
364   const int extra = LUA_MINSTACK;
365   if (!lua_checkstack(L, space + extra)) {
366     if (msg)
367       luaL_error(L, "stack overflow (%s)", msg);
368     else
369       luaL_error(L, "stack overflow");
370   }
371 }
372 
373 
374 LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
375   if (lua_type(L, arg) != t)
376     tag_error(L, arg, t);
377 }
378 
379 
380 LUALIB_API void luaL_checkany (lua_State *L, int arg) {
381   if (lua_type(L, arg) == LUA_TNONE)
382     luaL_argerror(L, arg, "value expected");
383 }
384 
385 
386 LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
387   const char *s = lua_tolstring(L, arg, len);
388   if (!s) tag_error(L, arg, LUA_TSTRING);
389   return s;
390 }
391 
392 
393 LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
394                                         const char *def, size_t *len) {
395   if (lua_isnoneornil(L, arg)) {
396     if (len)
397       *len = (def ? strlen(def) : 0);
398     return def;
399   }
400   else return luaL_checklstring(L, arg, len);
401 }
402 
403 
404 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
405   int isnum;
406   lua_Number d = lua_tonumberx(L, arg, &isnum);
407   if (!isnum)
408     tag_error(L, arg, LUA_TNUMBER);
409   return d;
410 }
411 
412 
413 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
414   return luaL_opt(L, luaL_checknumber, arg, def);
415 }
416 
417 
418 #ifndef _KERNEL
419 static void interror (lua_State *L, int arg) {
420   if (lua_isnumber(L, arg))
421     luaL_argerror(L, arg, "number has no integer representation");
422   else
423     tag_error(L, arg, LUA_TNUMBER);
424 }
425 
426 
427 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
428   int isnum;
429   lua_Integer d = lua_tointegerx(L, arg, &isnum);
430   if (!isnum) {
431     interror(L, arg);
432   }
433   return d;
434 }
435 
436 
437 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
438                                                       lua_Integer def) {
439   return luaL_opt(L, luaL_checkinteger, arg, def);
440 }
441 #endif /* _KERNEL */
442 
443 /* }====================================================== */
444 
445 
446 /*
447 ** {======================================================
448 ** Generic Buffer manipulation
449 ** =======================================================
450 */
451 
452 /* userdata to box arbitrary data */
453 typedef struct UBox {
454   void *box;
455   size_t bsize;
456 } UBox;
457 
458 
459 static void *resizebox (lua_State *L, int idx, size_t newsize) {
460   void *ud;
461   lua_Alloc allocf = lua_getallocf(L, &ud);
462   UBox *box = (UBox *)lua_touserdata(L, idx);
463   void *temp = allocf(ud, box->box, box->bsize, newsize);
464   if (temp == NULL && newsize > 0) {  /* allocation error? */
465     resizebox(L, idx, 0);  /* free buffer */
466     luaL_error(L, "not enough memory for buffer allocation");
467   }
468   box->box = temp;
469   box->bsize = newsize;
470   return temp;
471 }
472 
473 
474 static int boxgc (lua_State *L) {
475   resizebox(L, 1, 0);
476   return 0;
477 }
478 
479 
480 static void *newbox (lua_State *L, size_t newsize) {
481   UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));
482   box->box = NULL;
483   box->bsize = 0;
484   if (luaL_newmetatable(L, "LUABOX")) {  /* creating metatable? */
485     lua_pushcfunction(L, boxgc);
486     lua_setfield(L, -2, "__gc");  /* metatable.__gc = boxgc */
487   }
488   lua_setmetatable(L, -2);
489   return resizebox(L, -1, newsize);
490 }
491 
492 
493 /*
494 ** check whether buffer is using a userdata on the stack as a temporary
495 ** buffer
496 */
497 #define buffonstack(B)	((B)->b != (B)->initb)
498 
499 
500 /*
501 ** returns a pointer to a free area with at least 'sz' bytes
502 */
503 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
504   lua_State *L = B->L;
505   if (B->size - B->n < sz) {  /* not enough space? */
506     char *newbuff;
507     size_t newsize = B->size * 2;  /* double buffer size */
508     if (newsize - B->n < sz)  /* not big enough? */
509       newsize = B->n + sz;
510     if (newsize < B->n || newsize - B->n < sz)
511       luaL_error(L, "buffer too large");
512     /* create larger buffer */
513     if (buffonstack(B))
514       newbuff = (char *)resizebox(L, -1, newsize);
515     else {  /* no buffer yet */
516       newbuff = (char *)newbox(L, newsize);
517       memcpy(newbuff, B->b, B->n * sizeof(char));  /* copy original content */
518     }
519     B->b = newbuff;
520     B->size = newsize;
521   }
522   return &B->b[B->n];
523 }
524 
525 
526 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
527   if (l > 0) {  /* avoid 'memcpy' when 's' can be NULL */
528     char *b = luaL_prepbuffsize(B, l);
529     memcpy(b, s, l * sizeof(char));
530     luaL_addsize(B, l);
531   }
532 }
533 
534 
535 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
536   luaL_addlstring(B, s, strlen(s));
537 }
538 
539 
540 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
541   lua_State *L = B->L;
542   lua_pushlstring(L, B->b, B->n);
543   if (buffonstack(B)) {
544     resizebox(L, -2, 0);  /* delete old buffer */
545     lua_remove(L, -2);  /* remove its header from the stack */
546   }
547 }
548 
549 
550 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
551   luaL_addsize(B, sz);
552   luaL_pushresult(B);
553 }
554 
555 
556 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
557   lua_State *L = B->L;
558   size_t l;
559   const char *s = lua_tolstring(L, -1, &l);
560   if (buffonstack(B))
561     lua_insert(L, -2);  /* put value below buffer */
562   luaL_addlstring(B, s, l);
563   lua_remove(L, (buffonstack(B)) ? -2 : -1);  /* remove value */
564 }
565 
566 
567 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
568   B->L = L;
569   B->b = B->initb;
570   B->n = 0;
571   B->size = LUAL_BUFFERSIZE;
572 }
573 
574 
575 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
576   luaL_buffinit(L, B);
577   return luaL_prepbuffsize(B, sz);
578 }
579 
580 /* }====================================================== */
581 
582 
583 /*
584 ** {======================================================
585 ** Reference system
586 ** =======================================================
587 */
588 
589 /* index of free-list header */
590 #define freelist	0
591 
592 
593 LUALIB_API int luaL_ref (lua_State *L, int t) {
594   int ref;
595   if (lua_isnil(L, -1)) {
596     lua_pop(L, 1);  /* remove from stack */
597     return LUA_REFNIL;  /* 'nil' has a unique fixed reference */
598   }
599   t = lua_absindex(L, t);
600   lua_rawgeti(L, t, freelist);  /* get first free element */
601   ref = (int)lua_tointeger(L, -1);  /* ref = t[freelist] */
602   lua_pop(L, 1);  /* remove it from stack */
603   if (ref != 0) {  /* any free element? */
604     lua_rawgeti(L, t, ref);  /* remove it from list */
605     lua_rawseti(L, t, freelist);  /* (t[freelist] = t[ref]) */
606   }
607   else  /* no free elements */
608     ref = (int)lua_rawlen(L, t) + 1;  /* get a new reference */
609   lua_rawseti(L, t, ref);
610   return ref;
611 }
612 
613 
614 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
615   if (ref >= 0) {
616     t = lua_absindex(L, t);
617     lua_rawgeti(L, t, freelist);
618     lua_rawseti(L, t, ref);  /* t[ref] = t[freelist] */
619     lua_pushinteger(L, ref);
620     lua_rawseti(L, t, freelist);  /* t[freelist] = ref */
621   }
622 }
623 
624 /* }====================================================== */
625 
626 
627 /*
628 ** {======================================================
629 ** Load functions
630 ** =======================================================
631 */
632 
633 #ifndef _KERNEL
634 typedef struct LoadF {
635   int n;  /* number of pre-read characters */
636   FILE *f;  /* file being read */
637   char buff[BUFSIZ];  /* area for reading file */
638 } LoadF;
639 
640 
641 static const char *getF (lua_State *L, void *ud, size_t *size) {
642   LoadF *lf = (LoadF *)ud;
643   (void)L;  /* not used */
644   if (lf->n > 0) {  /* are there pre-read characters to be read? */
645     *size = lf->n;  /* return them (chars already in buffer) */
646     lf->n = 0;  /* no more pre-read characters */
647   }
648   else {  /* read a block from file */
649     /* 'fread' can return > 0 *and* set the EOF flag. If next call to
650        'getF' called 'fread', it might still wait for user input.
651        The next check avoids this problem. */
652     if (feof(lf->f)) return NULL;
653     *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);  /* read block */
654   }
655   return lf->buff;
656 }
657 
658 
659 static int errfile (lua_State *L, const char *what, int fnameindex) {
660   const char *serr = strerror(errno);
661   const char *filename = lua_tostring(L, fnameindex) + 1;
662   lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
663   lua_remove(L, fnameindex);
664   return LUA_ERRFILE;
665 }
666 
667 
668 static int skipBOM (LoadF *lf) {
669   const char *p = "\xEF\xBB\xBF";  /* UTF-8 BOM mark */
670   int c;
671   lf->n = 0;
672   do {
673     c = getc(lf->f);
674     if (c == EOF || c != *(const unsigned char *)p++) return c;
675     lf->buff[lf->n++] = c;  /* to be read by the parser */
676   } while (*p != '\0');
677   lf->n = 0;  /* prefix matched; discard it */
678   return getc(lf->f);  /* return next character */
679 }
680 
681 
682 /*
683 ** reads the first character of file 'f' and skips an optional BOM mark
684 ** in its beginning plus its first line if it starts with '#'. Returns
685 ** true if it skipped the first line.  In any case, '*cp' has the
686 ** first "valid" character of the file (after the optional BOM and
687 ** a first-line comment).
688 */
689 static int skipcomment (LoadF *lf, int *cp) {
690   int c = *cp = skipBOM(lf);
691   if (c == '#') {  /* first line is a comment (Unix exec. file)? */
692     do {  /* skip first line */
693       c = getc(lf->f);
694     } while (c != EOF && c != '\n') ;
695     *cp = getc(lf->f);  /* skip end-of-line, if present */
696     return 1;  /* there was a comment */
697   }
698   else return 0;  /* no comment */
699 }
700 
701 
702 LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
703                                              const char *mode) {
704   LoadF lf;
705   int status, readstatus;
706   int c;
707   int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
708   if (filename == NULL) {
709     lua_pushliteral(L, "=stdin");
710     lf.f = stdin;
711   }
712   else {
713     lua_pushfstring(L, "@%s", filename);
714     lf.f = fopen(filename, "r");
715     if (lf.f == NULL) return errfile(L, "open", fnameindex);
716   }
717   if (skipcomment(&lf, &c))  /* read initial portion */
718     lf.buff[lf.n++] = '\n';  /* add line to correct line numbers */
719   if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */
720     lf.f = freopen(filename, "rb", lf.f);  /* reopen in binary mode */
721     if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
722     skipcomment(&lf, &c);  /* re-read initial portion */
723   }
724   if (c != EOF)
725     lf.buff[lf.n++] = c;  /* 'c' is the first character of the stream */
726   status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
727   readstatus = ferror(lf.f);
728   if (filename) fclose(lf.f);  /* close file (even in case of errors) */
729   if (readstatus) {
730     lua_settop(L, fnameindex);  /* ignore results from 'lua_load' */
731     return errfile(L, "read", fnameindex);
732   }
733   lua_remove(L, fnameindex);
734   return status;
735 }
736 #endif /* _KERNEL */
737 
738 
739 typedef struct LoadS {
740   const char *s;
741   size_t size;
742 } LoadS;
743 
744 
745 static const char *getS (lua_State *L, void *ud, size_t *size) {
746   LoadS *ls = (LoadS *)ud;
747   (void)L;  /* not used */
748   if (ls->size == 0) return NULL;
749   *size = ls->size;
750   ls->size = 0;
751   return ls->s;
752 }
753 
754 
755 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
756                                  const char *name, const char *mode) {
757   LoadS ls;
758   ls.s = buff;
759   ls.size = size;
760   return lua_load(L, getS, &ls, name, mode);
761 }
762 
763 
764 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
765   return luaL_loadbuffer(L, s, strlen(s), s);
766 }
767 
768 /* }====================================================== */
769 
770 
771 
772 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
773   if (!lua_getmetatable(L, obj))  /* no metatable? */
774     return LUA_TNIL;
775   else {
776     int tt;
777     lua_pushstring(L, event);
778     tt = lua_rawget(L, -2);
779     if (tt == LUA_TNIL)  /* is metafield nil? */
780       lua_pop(L, 2);  /* remove metatable and metafield */
781     else
782       lua_remove(L, -2);  /* remove only metatable */
783     return tt;  /* return metafield type */
784   }
785 }
786 
787 
788 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
789   obj = lua_absindex(L, obj);
790   if (luaL_getmetafield(L, obj, event) == LUA_TNIL)  /* no metafield? */
791     return 0;
792   lua_pushvalue(L, obj);
793   lua_call(L, 1, 1);
794   return 1;
795 }
796 
797 
798 LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
799   lua_Integer l;
800   int isnum;
801   lua_len(L, idx);
802   l = lua_tointegerx(L, -1, &isnum);
803   if (!isnum)
804     luaL_error(L, "object length is not an integer");
805   lua_pop(L, 1);  /* remove object */
806   return l;
807 }
808 
809 
810 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
811   if (!luaL_callmeta(L, idx, "__tostring")) {  /* no metafield? */
812     switch (lua_type(L, idx)) {
813       case LUA_TNUMBER: {
814         if (lua_isinteger(L, idx))
815           lua_pushfstring(L, "%I", lua_tointeger(L, idx));
816         else
817           lua_pushfstring(L, "%f", lua_tonumber(L, idx));
818         break;
819       }
820       case LUA_TSTRING:
821         lua_pushvalue(L, idx);
822         break;
823       case LUA_TBOOLEAN:
824         lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
825         break;
826       case LUA_TNIL:
827         lua_pushliteral(L, "nil");
828         break;
829       default:
830         lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
831                                             lua_topointer(L, idx));
832         break;
833     }
834   }
835   return lua_tolstring(L, -1, len);
836 }
837 
838 
839 /*
840 ** {======================================================
841 ** Compatibility with 5.1 module functions
842 ** =======================================================
843 */
844 #if defined(LUA_COMPAT_MODULE)
845 
846 static const char *luaL_findtable (lua_State *L, int idx,
847                                    const char *fname, int szhint) {
848   const char *e;
849   if (idx) lua_pushvalue(L, idx);
850   do {
851     e = strchr(fname, '.');
852     if (e == NULL) e = fname + strlen(fname);
853     lua_pushlstring(L, fname, e - fname);
854     if (lua_rawget(L, -2) == LUA_TNIL) {  /* no such field? */
855       lua_pop(L, 1);  /* remove this nil */
856       lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
857       lua_pushlstring(L, fname, e - fname);
858       lua_pushvalue(L, -2);
859       lua_settable(L, -4);  /* set new table into field */
860     }
861     else if (!lua_istable(L, -1)) {  /* field has a non-table value? */
862       lua_pop(L, 2);  /* remove table and value */
863       return fname;  /* return problematic part of the name */
864     }
865     lua_remove(L, -2);  /* remove previous table */
866     fname = e + 1;
867   } while (*e == '.');
868   return NULL;
869 }
870 
871 
872 /*
873 ** Count number of elements in a luaL_Reg list.
874 */
875 static int libsize (const luaL_Reg *l) {
876   int size = 0;
877   for (; l && l->name; l++) size++;
878   return size;
879 }
880 
881 
882 /*
883 ** Find or create a module table with a given name. The function
884 ** first looks at the _LOADED table and, if that fails, try a
885 ** global variable with that name. In any case, leaves on the stack
886 ** the module table.
887 */
888 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
889                                  int sizehint) {
890   luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);  /* get _LOADED table */
891   if (lua_getfield(L, -1, modname) != LUA_TTABLE) {  /* no _LOADED[modname]? */
892     lua_pop(L, 1);  /* remove previous result */
893     /* try global variable (and create one if it does not exist) */
894     lua_pushglobaltable(L);
895     if (luaL_findtable(L, 0, modname, sizehint) != NULL)
896       luaL_error(L, "name conflict for module '%s'", modname);
897     lua_pushvalue(L, -1);
898     lua_setfield(L, -3, modname);  /* _LOADED[modname] = new table */
899   }
900   lua_remove(L, -2);  /* remove _LOADED table */
901 }
902 
903 
904 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
905                                const luaL_Reg *l, int nup) {
906   luaL_checkversion(L);
907   if (libname) {
908     luaL_pushmodule(L, libname, libsize(l));  /* get/create library table */
909     lua_insert(L, -(nup + 1));  /* move library table to below upvalues */
910   }
911   if (l)
912     luaL_setfuncs(L, l, nup);
913   else
914     lua_pop(L, nup);  /* remove upvalues */
915 }
916 
917 #endif
918 /* }====================================================== */
919 
920 /*
921 ** set functions from list 'l' into table at top - 'nup'; each
922 ** function gets the 'nup' elements at the top as upvalues.
923 ** Returns with only the table at the stack.
924 */
925 LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
926   luaL_checkstack(L, nup, "too many upvalues");
927   for (; l->name != NULL; l++) {  /* fill the table with given functions */
928     int i;
929     for (i = 0; i < nup; i++)  /* copy upvalues to the top */
930       lua_pushvalue(L, -nup);
931     lua_pushcclosure(L, l->func, nup);  /* closure with those upvalues */
932     lua_setfield(L, -(nup + 2), l->name);
933   }
934   lua_pop(L, nup);  /* remove upvalues */
935 }
936 
937 
938 /*
939 ** ensure that stack[idx][fname] has a table and push that table
940 ** into the stack
941 */
942 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
943   if (lua_getfield(L, idx, fname) == LUA_TTABLE)
944     return 1;  /* table already there */
945   else {
946     lua_pop(L, 1);  /* remove previous result */
947     idx = lua_absindex(L, idx);
948     lua_newtable(L);
949     lua_pushvalue(L, -1);  /* copy to be left at top */
950     lua_setfield(L, idx, fname);  /* assign new table to field */
951     return 0;  /* false, because did not find table there */
952   }
953 }
954 
955 
956 /*
957 ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
958 ** to open a module, registers the result in 'package.loaded' table and,
959 ** if 'glb' is true, also registers the result in the global table.
960 ** Leaves resulting module on the top.
961 */
962 LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
963                                lua_CFunction openf, int glb) {
964   luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
965   lua_getfield(L, -1, modname);  /* _LOADED[modname] */
966   if (!lua_toboolean(L, -1)) {  /* package not already loaded? */
967     lua_pop(L, 1);  /* remove field */
968     lua_pushcfunction(L, openf);
969     lua_pushstring(L, modname);  /* argument to open function */
970     lua_call(L, 1, 1);  /* call 'openf' to open module */
971     lua_pushvalue(L, -1);  /* make copy of module (call result) */
972     lua_setfield(L, -3, modname);  /* _LOADED[modname] = module */
973   }
974   lua_remove(L, -2);  /* remove _LOADED table */
975   if (glb) {
976     lua_pushvalue(L, -1);  /* copy of module */
977     lua_setglobal(L, modname);  /* _G[modname] = module */
978   }
979 }
980 
981 
982 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
983                                                                const char *r) {
984   const char *wild;
985   size_t l = strlen(p);
986   luaL_Buffer b;
987   luaL_buffinit(L, &b);
988   while ((wild = strstr(s, p)) != NULL) {
989     luaL_addlstring(&b, s, wild - s);  /* push prefix */
990     luaL_addstring(&b, r);  /* push replacement in place of pattern */
991     s = wild + l;  /* continue after 'p' */
992   }
993   luaL_addstring(&b, s);  /* push last suffix */
994   luaL_pushresult(&b);
995   return lua_tostring(L, -1);
996 }
997 
998 
999 #ifndef _KERNEL
1000 static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1001   (void)ud; (void)osize;  /* not used */
1002   if (nsize == 0) {
1003     free(ptr);
1004     return NULL;
1005   }
1006   else
1007     return realloc(ptr, nsize);
1008 }
1009 
1010 
1011 static int panic (lua_State *L) {
1012   lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
1013                         lua_tostring(L, -1));
1014   return 0;  /* return to Lua to abort */
1015 }
1016 
1017 
1018 LUALIB_API lua_State *luaL_newstate (void) {
1019   lua_State *L = lua_newstate(l_alloc, NULL);
1020   if (L) lua_atpanic(L, &panic);
1021   return L;
1022 }
1023 #endif /* _KERNEL */
1024 
1025 
1026 LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
1027   const lua_Number *v = lua_version(L);
1028   if (sz != LUAL_NUMSIZES)  /* check numeric types */
1029     luaL_error(L, "core and library have incompatible numeric types");
1030   if (v != lua_version(NULL))
1031     luaL_error(L, "multiple Lua VMs detected");
1032   else if (*v != ver)
1033     luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
1034                   ver, *v);
1035 }
1036 
1037