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