2 ** $Id: lauxlib.c,v 1.286 2016/01/08 15:33:09 roberto Exp $
3 ** Auxiliary functions for building Lua libraries
4 ** See Copyright Notice in lua.h
21 ** This file uses only the official API of Lua.
22 ** Any function declared here could be written as an application function.
31 ** {======================================================
33 ** =======================================================
37 #define LEVELS1 10 /* size of the first part of the stack */
38 #define LEVELS2 11 /* size of the second part of the stack */
43 ** search for 'objidx' in table at index -1.
44 ** return 1 + string at top if find a good name.
46 static int findfield (lua_State *L, int objidx, int level) {
47 if (level == 0 || !lua_istable(L, -1))
48 return 0; /* not found */
49 lua_pushnil(L); /* start 'next' loop */
50 while (lua_next(L, -2)) { /* for each pair in table */
51 if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
52 if (lua_rawequal(L, objidx, -1)) { /* found object? */
53 lua_pop(L, 1); /* remove value (but keep name) */
56 else if (findfield(L, objidx, level - 1)) { /* try recursively */
57 lua_remove(L, -2); /* remove table (but keep name) */
58 lua_pushliteral(L, ".");
59 lua_insert(L, -2); /* place '.' between the two names */
64 lua_pop(L, 1); /* remove value */
66 return 0; /* not found */
71 ** Search for a name for a function in all loaded modules
72 ** (registry._LOADED).
74 static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
75 int top = lua_gettop(L);
76 lua_getinfo(L, "f", ar); /* push function */
77 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
78 if (findfield(L, top + 1, 2)) {
79 const char *name = lua_tostring(L, -1);
80 if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */
81 lua_pushstring(L, name + 3); /* push name without prefix */
82 lua_remove(L, -2); /* remove original name */
84 lua_copy(L, -1, top + 1); /* move name to proper place */
85 lua_pop(L, 2); /* remove pushed values */
89 lua_settop(L, top); /* remove function and global table */
95 static void pushfuncname (lua_State *L, lua_Debug *ar) {
96 if (pushglobalfuncname(L, ar)) { /* try first a global name */
97 lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
98 lua_remove(L, -2); /* remove name */
100 else if (*ar->namewhat != '\0') /* is there a name from code? */
101 lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
102 else if (*ar->what == 'm') /* main? */
103 lua_pushliteral(L, "main chunk");
104 else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
105 lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
106 else /* nothing left... */
107 lua_pushliteral(L, "?");
111 static int lastlevel (lua_State *L) {
114 /* find an upper bound */
115 while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
116 /* do a binary search */
119 if (lua_getstack(L, m, &ar)) li = m + 1;
126 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
127 const char *msg, int level) {
129 int top = lua_gettop(L);
130 int last = lastlevel(L1);
131 int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
133 lua_pushfstring(L, "%s\n", msg);
134 luaL_checkstack(L, 10, NULL);
135 lua_pushliteral(L, "stack traceback:");
136 while (lua_getstack(L1, level++, &ar)) {
137 if (n1-- == 0) { /* too many levels? */
138 lua_pushliteral(L, "\n\t..."); /* add a '...' */
139 level = last - LEVELS2 + 1; /* and skip to last ones */
142 lua_getinfo(L1, "Slnt", &ar);
143 lua_pushfstring(L, "\n\t%s:", ar.short_src);
144 if (ar.currentline > 0)
145 lua_pushfstring(L, "%d:", ar.currentline);
146 lua_pushliteral(L, " in ");
147 pushfuncname(L, &ar);
149 lua_pushliteral(L, "\n\t(...tail calls...)");
150 lua_concat(L, lua_gettop(L) - top);
153 lua_concat(L, lua_gettop(L) - top);
156 /* }====================================================== */
160 ** {======================================================
161 ** Error-report functions
162 ** =======================================================
165 LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
167 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
168 return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
169 lua_getinfo(L, "n", &ar);
170 if (strcmp(ar.namewhat, "method") == 0) {
171 arg--; /* do not count 'self' */
172 if (arg == 0) /* error is in the self argument itself? */
173 return luaL_error(L, "calling '%s' on bad self (%s)",
177 ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
178 return luaL_error(L, "bad argument #%d to '%s' (%s)",
179 arg, ar.name, extramsg);
183 static int typeerror (lua_State *L, int arg, const char *tname) {
185 const char *typearg; /* name for the type of the actual argument */
186 if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
187 typearg = lua_tostring(L, -1); /* use the given type name */
188 else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
189 typearg = "light userdata"; /* special name for messages */
191 typearg = luaL_typename(L, arg); /* standard name */
192 msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
193 return luaL_argerror(L, arg, msg);
197 static void tag_error (lua_State *L, int arg, int tag) {
198 typeerror(L, arg, lua_typename(L, tag));
203 ** The use of 'lua_pushfstring' ensures this function does not
204 ** need reserved stack space when called.
206 LUALIB_API void luaL_where (lua_State *L, int level) {
208 if (lua_getstack(L, level, &ar)) { /* check function at level */
209 lua_getinfo(L, "Sl", &ar); /* get info about it */
210 if (ar.currentline > 0) { /* is there info? */
211 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
215 lua_pushfstring(L, ""); /* else, no information available... */
220 ** Again, the use of 'lua_pushvfstring' ensures this function does
221 ** not need reserved stack space when called. (At worst, it generates
222 ** an error with "stack overflow" instead of the given message.)
224 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
228 lua_pushvfstring(L, fmt, argp);
235 LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
236 int en = errno; /* calls to Lua API may change this value */
238 lua_pushboolean(L, 1);
244 lua_pushfstring(L, "%s: %s", fname, strerror(en));
246 lua_pushstring(L, strerror(en));
247 lua_pushinteger(L, en);
253 #if !defined(l_inspectstat) /* { */
255 #if defined(LUA_USE_POSIX)
257 #include <sys/wait.h>
260 ** use appropriate macros to interpret 'pclose' return status
262 #define l_inspectstat(stat,what) \
263 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
264 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
268 #define l_inspectstat(stat,what) /* no op */
275 LUALIB_API int luaL_execresult (lua_State *L, int stat) {
276 const char *what = "exit"; /* type of termination */
277 if (stat == -1) /* error? */
278 return luaL_fileresult(L, 0, NULL);
280 l_inspectstat(stat, what); /* interpret result */
281 if (*what == 'e' && stat == 0) /* successful termination? */
282 lua_pushboolean(L, 1);
285 lua_pushstring(L, what);
286 lua_pushinteger(L, stat);
287 return 3; /* return true/nil,what,code */
291 /* }====================================================== */
295 ** {======================================================
296 ** Userdata's metatable manipulation
297 ** =======================================================
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 */
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 */
313 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
314 luaL_getmetatable(L, tname);
315 lua_setmetatable(L, -2);
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 */
330 return NULL; /* value is not a userdata with a metatable */
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);
340 /* }====================================================== */
344 ** {======================================================
345 ** Argument check functions
346 ** =======================================================
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);
354 for (i=0; lst[i]; i++)
355 if (strcmp(lst[i], name) == 0)
357 return luaL_argerror(L, arg,
358 lua_pushfstring(L, "invalid option '%s'", name));
363 ** Ensures the stack has at least 'space' extra slots, raising an error
364 ** if it cannot fulfill the request. (The error handling needs a few
365 ** extra slots to format the error message. In case of an error without
366 ** this extra space, Lua will generate the same 'stack overflow' error,
367 ** but without 'msg'.)
369 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
370 if (!lua_checkstack(L, space)) {
372 luaL_error(L, "stack overflow (%s)", msg);
374 luaL_error(L, "stack overflow");
379 LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
380 if (lua_type(L, arg) != t)
381 tag_error(L, arg, t);
385 LUALIB_API void luaL_checkany (lua_State *L, int arg) {
386 if (lua_type(L, arg) == LUA_TNONE)
387 luaL_argerror(L, arg, "value expected");
391 LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
392 const char *s = lua_tolstring(L, arg, len);
393 if (!s) tag_error(L, arg, LUA_TSTRING);
398 LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
399 const char *def, size_t *len) {
400 if (lua_isnoneornil(L, arg)) {
402 *len = (def ? strlen(def) : 0);
405 else return luaL_checklstring(L, arg, len);
409 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
411 lua_Number d = lua_tonumberx(L, arg, &isnum);
413 tag_error(L, arg, LUA_TNUMBER);
418 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
419 return luaL_opt(L, luaL_checknumber, arg, def);
423 static void interror (lua_State *L, int arg) {
424 if (lua_isnumber(L, arg))
425 luaL_argerror(L, arg, "number has no integer representation");
427 tag_error(L, arg, LUA_TNUMBER);
431 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
433 lua_Integer d = lua_tointegerx(L, arg, &isnum);
441 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
443 return luaL_opt(L, luaL_checkinteger, arg, def);
446 /* }====================================================== */
450 ** {======================================================
451 ** Generic Buffer manipulation
452 ** =======================================================
455 /* userdata to box arbitrary data */
456 typedef struct UBox {
462 static void *resizebox (lua_State *L, int idx, size_t newsize) {
464 lua_Alloc allocf = lua_getallocf(L, &ud);
465 UBox *box = (UBox *)lua_touserdata(L, idx);
466 void *temp = allocf(ud, box->box, box->bsize, newsize);
467 if (temp == NULL && newsize > 0) { /* allocation error? */
468 resizebox(L, idx, 0); /* free buffer */
469 luaL_error(L, "not enough memory for buffer allocation");
472 box->bsize = newsize;
477 static int boxgc (lua_State *L) {
483 static void *newbox (lua_State *L, size_t newsize) {
484 UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));
487 if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */
488 lua_pushcfunction(L, boxgc);
489 lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */
491 lua_setmetatable(L, -2);
492 return resizebox(L, -1, newsize);
497 ** check whether buffer is using a userdata on the stack as a temporary
500 #define buffonstack(B) ((B)->b != (B)->initb)
504 ** returns a pointer to a free area with at least 'sz' bytes
506 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
508 if (B->size - B->n < sz) { /* not enough space? */
510 size_t newsize = B->size * 2; /* double buffer size */
511 if (newsize - B->n < sz) /* not big enough? */
513 if (newsize < B->n || newsize - B->n < sz)
514 luaL_error(L, "buffer too large");
515 /* create larger buffer */
517 newbuff = (char *)resizebox(L, -1, newsize);
518 else { /* no buffer yet */
519 newbuff = (char *)newbox(L, newsize);
520 memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
529 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
530 if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
531 char *b = luaL_prepbuffsize(B, l);
532 memcpy(b, s, l * sizeof(char));
538 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
539 luaL_addlstring(B, s, strlen(s));
543 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
545 lua_pushlstring(L, B->b, B->n);
546 if (buffonstack(B)) {
547 resizebox(L, -2, 0); /* delete old buffer */
548 lua_remove(L, -2); /* remove its header from the stack */
553 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
559 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
562 const char *s = lua_tolstring(L, -1, &l);
564 lua_insert(L, -2); /* put value below buffer */
565 luaL_addlstring(B, s, l);
566 lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
570 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
574 B->size = LUAL_BUFFERSIZE;
578 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
580 return luaL_prepbuffsize(B, sz);
583 /* }====================================================== */
587 ** {======================================================
589 ** =======================================================
592 /* index of free-list header */
596 LUALIB_API int luaL_ref (lua_State *L, int t) {
598 if (lua_isnil(L, -1)) {
599 lua_pop(L, 1); /* remove from stack */
600 return LUA_REFNIL; /* 'nil' has a unique fixed reference */
602 t = lua_absindex(L, t);
603 lua_rawgeti(L, t, freelist); /* get first free element */
604 ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
605 lua_pop(L, 1); /* remove it from stack */
606 if (ref != 0) { /* any free element? */
607 lua_rawgeti(L, t, ref); /* remove it from list */
608 lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
610 else /* no free elements */
611 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
612 lua_rawseti(L, t, ref);
617 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
619 t = lua_absindex(L, t);
620 lua_rawgeti(L, t, freelist);
621 lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
622 lua_pushinteger(L, ref);
623 lua_rawseti(L, t, freelist); /* t[freelist] = ref */
627 /* }====================================================== */
631 ** {======================================================
633 ** =======================================================
636 typedef struct LoadF {
637 int n; /* number of pre-read characters */
638 FILE *f; /* file being read */
639 char buff[BUFSIZ]; /* area for reading file */
643 static const char *getF (lua_State *L, void *ud, size_t *size) {
644 LoadF *lf = (LoadF *)ud;
645 (void)L; /* not used */
646 if (lf->n > 0) { /* are there pre-read characters to be read? */
647 *size = lf->n; /* return them (chars already in buffer) */
648 lf->n = 0; /* no more pre-read characters */
650 else { /* read a block from file */
651 /* 'fread' can return > 0 *and* set the EOF flag. If next call to
652 'getF' called 'fread', it might still wait for user input.
653 The next check avoids this problem. */
654 if (feof(lf->f)) return NULL;
655 *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
661 static int errfile (lua_State *L, const char *what, int fnameindex) {
662 const char *serr = strerror(errno);
663 const char *filename = lua_tostring(L, fnameindex) + 1;
664 lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
665 lua_remove(L, fnameindex);
670 static int skipBOM (LoadF *lf) {
671 const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
676 if (c == EOF || c != *(const unsigned char *)p++) return c;
677 lf->buff[lf->n++] = c; /* to be read by the parser */
678 } while (*p != '\0');
679 lf->n = 0; /* prefix matched; discard it */
680 return getc(lf->f); /* return next character */
685 ** reads the first character of file 'f' and skips an optional BOM mark
686 ** in its beginning plus its first line if it starts with '#'. Returns
687 ** true if it skipped the first line. In any case, '*cp' has the
688 ** first "valid" character of the file (after the optional BOM and
689 ** a first-line comment).
691 static int skipcomment (LoadF *lf, int *cp) {
692 int c = *cp = skipBOM(lf);
693 if (c == '#') { /* first line is a comment (Unix exec. file)? */
694 do { /* skip first line */
696 } while (c != EOF && c != '\n');
697 *cp = getc(lf->f); /* skip end-of-line, if present */
698 return 1; /* there was a comment */
700 else return 0; /* no comment */
704 LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
707 int status, readstatus;
709 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
710 if (filename == NULL) {
711 lua_pushliteral(L, "=stdin");
715 lua_pushfstring(L, "@%s", filename);
716 lf.f = fopen(filename, "r");
717 if (lf.f == NULL) return errfile(L, "open", fnameindex);
719 if (skipcomment(&lf, &c)) /* read initial portion */
720 lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
721 if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
722 lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
723 if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
724 skipcomment(&lf, &c); /* re-read initial portion */
727 lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
728 status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
729 readstatus = ferror(lf.f);
730 if (filename) fclose(lf.f); /* close file (even in case of errors) */
732 lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
733 return errfile(L, "read", fnameindex);
735 lua_remove(L, fnameindex);
740 typedef struct LoadS {
746 static const char *getS (lua_State *L, void *ud, size_t *size) {
747 LoadS *ls = (LoadS *)ud;
748 (void)L; /* not used */
749 if (ls->size == 0) return NULL;
756 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
757 const char *name, const char *mode) {
761 return lua_load(L, getS, &ls, name, mode);
765 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
766 return luaL_loadbuffer(L, s, strlen(s), s);
769 /* }====================================================== */
773 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
774 if (!lua_getmetatable(L, obj)) /* no metatable? */
778 lua_pushstring(L, event);
779 tt = lua_rawget(L, -2);
780 if (tt == LUA_TNIL) /* is metafield nil? */
781 lua_pop(L, 2); /* remove metatable and metafield */
783 lua_remove(L, -2); /* remove only metatable */
784 return tt; /* return metafield type */
789 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
790 obj = lua_absindex(L, obj);
791 if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
793 lua_pushvalue(L, obj);
799 LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
803 l = lua_tointegerx(L, -1, &isnum);
805 luaL_error(L, "object length is not an integer");
806 lua_pop(L, 1); /* remove object */
811 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
812 if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
813 switch (lua_type(L, idx)) {
815 if (lua_isinteger(L, idx))
816 lua_pushfstring(L, "%I", lua_tointeger(L, idx));
818 lua_pushfstring(L, "%f", lua_tonumber(L, idx));
822 lua_pushvalue(L, idx);
825 lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
828 lua_pushliteral(L, "nil");
831 lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
832 lua_topointer(L, idx));
836 return lua_tolstring(L, -1, len);
841 ** {======================================================
842 ** Compatibility with 5.1 module functions
843 ** =======================================================
845 #if defined(LUA_COMPAT_MODULE)
847 static const char *luaL_findtable (lua_State *L, int idx,
848 const char *fname, int szhint) {
850 if (idx) lua_pushvalue(L, idx);
852 e = strchr(fname, '.');
853 if (e == NULL) e = fname + strlen(fname);
854 lua_pushlstring(L, fname, e - fname);
855 if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
856 lua_pop(L, 1); /* remove this nil */
857 lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
858 lua_pushlstring(L, fname, e - fname);
859 lua_pushvalue(L, -2);
860 lua_settable(L, -4); /* set new table into field */
862 else if (!lua_istable(L, -1)) { /* field has a non-table value? */
863 lua_pop(L, 2); /* remove table and value */
864 return fname; /* return problematic part of the name */
866 lua_remove(L, -2); /* remove previous table */
874 ** Count number of elements in a luaL_Reg list.
876 static int libsize (const luaL_Reg *l) {
878 for (; l && l->name; l++) size++;
884 ** Find or create a module table with a given name. The function
885 ** first looks at the _LOADED table and, if that fails, try a
886 ** global variable with that name. In any case, leaves on the stack
889 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
891 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
892 if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no _LOADED[modname]? */
893 lua_pop(L, 1); /* remove previous result */
894 /* try global variable (and create one if it does not exist) */
895 lua_pushglobaltable(L);
896 if (luaL_findtable(L, 0, modname, sizehint) != NULL)
897 luaL_error(L, "name conflict for module '%s'", modname);
898 lua_pushvalue(L, -1);
899 lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
901 lua_remove(L, -2); /* remove _LOADED table */
905 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
906 const luaL_Reg *l, int nup) {
907 luaL_checkversion(L);
909 luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
910 lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
913 luaL_setfuncs(L, l, nup);
915 lua_pop(L, nup); /* remove upvalues */
919 /* }====================================================== */
922 ** set functions from list 'l' into table at top - 'nup'; each
923 ** function gets the 'nup' elements at the top as upvalues.
924 ** Returns with only the table at the stack.
926 LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
927 luaL_checkstack(L, nup, "too many upvalues");
928 for (; l->name != NULL; l++) { /* fill the table with given functions */
930 for (i = 0; i < nup; i++) /* copy upvalues to the top */
931 lua_pushvalue(L, -nup);
932 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
933 lua_setfield(L, -(nup + 2), l->name);
935 lua_pop(L, nup); /* remove upvalues */
940 ** ensure that stack[idx][fname] has a table and push that table
943 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
944 if (lua_getfield(L, idx, fname) == LUA_TTABLE)
945 return 1; /* table already there */
947 lua_pop(L, 1); /* remove previous result */
948 idx = lua_absindex(L, idx);
950 lua_pushvalue(L, -1); /* copy to be left at top */
951 lua_setfield(L, idx, fname); /* assign new table to field */
952 return 0; /* false, because did not find table there */
958 ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
959 ** to open a module, registers the result in 'package.loaded' table and,
960 ** if 'glb' is true, also registers the result in the global table.
961 ** Leaves resulting module on the top.
963 LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
964 lua_CFunction openf, int glb) {
965 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
966 lua_getfield(L, -1, modname); /* _LOADED[modname] */
967 if (!lua_toboolean(L, -1)) { /* package not already loaded? */
968 lua_pop(L, 1); /* remove field */
969 lua_pushcfunction(L, openf);
970 lua_pushstring(L, modname); /* argument to open function */
971 lua_call(L, 1, 1); /* call 'openf' to open module */
972 lua_pushvalue(L, -1); /* make copy of module (call result) */
973 lua_setfield(L, -3, modname); /* _LOADED[modname] = module */
975 lua_remove(L, -2); /* remove _LOADED table */
977 lua_pushvalue(L, -1); /* copy of module */
978 lua_setglobal(L, modname); /* _G[modname] = module */
983 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
986 size_t l = strlen(p);
988 luaL_buffinit(L, &b);
989 while ((wild = strstr(s, p)) != NULL) {
990 luaL_addlstring(&b, s, wild - s); /* push prefix */
991 luaL_addstring(&b, r); /* push replacement in place of pattern */
992 s = wild + l; /* continue after 'p' */
994 luaL_addstring(&b, s); /* push last suffix */
996 return lua_tostring(L, -1);
1000 static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1001 (void)ud; (void)osize; /* not used */
1007 return realloc(ptr, nsize);
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 */
1018 LUALIB_API lua_State *luaL_newstate (void) {
1019 lua_State *L = lua_newstate(l_alloc, NULL);
1020 if (L) lua_atpanic(L, &panic);
1025 LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
1026 const lua_Number *v = lua_version(L);
1027 if (sz != LUAL_NUMSIZES) /* check numeric types */
1028 luaL_error(L, "core and library have incompatible numeric types");
1029 if (v != lua_version(NULL))
1030 luaL_error(L, "multiple Lua VMs detected");
1032 luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",