2 ** $Id: lauxlib.c,v 1.289.1.1 2017/04/19 17:20:42 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
73 static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
74 int top = lua_gettop(L);
75 lua_getinfo(L, "f", ar); /* push function */
76 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
77 if (findfield(L, top + 1, 2)) {
78 const char *name = lua_tostring(L, -1);
79 if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */
80 lua_pushstring(L, name + 3); /* push name without prefix */
81 lua_remove(L, -2); /* remove original name */
83 lua_copy(L, -1, top + 1); /* move name to proper place */
84 lua_pop(L, 2); /* remove pushed values */
88 lua_settop(L, top); /* remove function and global table */
94 static void pushfuncname (lua_State *L, lua_Debug *ar) {
95 if (pushglobalfuncname(L, ar)) { /* try first a global name */
96 lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
97 lua_remove(L, -2); /* remove name */
99 else if (*ar->namewhat != '\0') /* is there a name from code? */
100 lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
101 else if (*ar->what == 'm') /* main? */
102 lua_pushliteral(L, "main chunk");
103 else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
104 lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
105 else /* nothing left... */
106 lua_pushliteral(L, "?");
110 static int lastlevel (lua_State *L) {
113 /* find an upper bound */
114 while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
115 /* do a binary search */
118 if (lua_getstack(L, m, &ar)) li = m + 1;
125 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
126 const char *msg, int level) {
128 int top = lua_gettop(L);
129 int last = lastlevel(L1);
130 int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
132 lua_pushfstring(L, "%s\n", msg);
133 luaL_checkstack(L, 10, NULL);
134 lua_pushliteral(L, "stack traceback:");
135 while (lua_getstack(L1, level++, &ar)) {
136 if (n1-- == 0) { /* too many levels? */
137 lua_pushliteral(L, "\n\t..."); /* add a '...' */
138 level = last - LEVELS2 + 1; /* and skip to last ones */
141 lua_getinfo(L1, "Slnt", &ar);
142 lua_pushfstring(L, "\n\t%s:", ar.short_src);
143 if (ar.currentline > 0)
144 lua_pushfstring(L, "%d:", ar.currentline);
145 lua_pushliteral(L, " in ");
146 pushfuncname(L, &ar);
148 lua_pushliteral(L, "\n\t(...tail calls...)");
149 lua_concat(L, lua_gettop(L) - top);
152 lua_concat(L, lua_gettop(L) - top);
155 /* }====================================================== */
159 ** {======================================================
160 ** Error-report functions
161 ** =======================================================
164 LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
166 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
167 return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
168 lua_getinfo(L, "n", &ar);
169 if (strcmp(ar.namewhat, "method") == 0) {
170 arg--; /* do not count 'self' */
171 if (arg == 0) /* error is in the self argument itself? */
172 return luaL_error(L, "calling '%s' on bad self (%s)",
176 ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
177 return luaL_error(L, "bad argument #%d to '%s' (%s)",
178 arg, ar.name, extramsg);
182 static int typeerror (lua_State *L, int arg, const char *tname) {
184 const char *typearg; /* name for the type of the actual argument */
185 if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
186 typearg = lua_tostring(L, -1); /* use the given type name */
187 else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
188 typearg = "light userdata"; /* special name for messages */
190 typearg = luaL_typename(L, arg); /* standard name */
191 msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
192 return luaL_argerror(L, arg, msg);
196 static void tag_error (lua_State *L, int arg, int tag) {
197 typeerror(L, arg, lua_typename(L, tag));
202 ** The use of 'lua_pushfstring' ensures this function does not
203 ** need reserved stack space when called.
205 LUALIB_API void luaL_where (lua_State *L, int level) {
207 if (lua_getstack(L, level, &ar)) { /* check function at level */
208 lua_getinfo(L, "Sl", &ar); /* get info about it */
209 if (ar.currentline > 0) { /* is there info? */
210 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
214 lua_pushfstring(L, ""); /* else, no information available... */
219 ** Again, the use of 'lua_pushvfstring' ensures this function does
220 ** not need reserved stack space when called. (At worst, it generates
221 ** an error with "stack overflow" instead of the given message.)
223 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
227 lua_pushvfstring(L, fmt, argp);
234 LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
235 int en = errno; /* calls to Lua API may change this value */
237 lua_pushboolean(L, 1);
243 lua_pushfstring(L, "%s: %s", fname, strerror(en));
245 lua_pushstring(L, strerror(en));
246 lua_pushinteger(L, en);
252 #if !defined(l_inspectstat) /* { */
254 #if defined(LUA_USE_POSIX)
256 #include <sys/wait.h>
259 ** use appropriate macros to interpret 'pclose' return status
261 #define l_inspectstat(stat,what) \
262 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
263 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
267 #define l_inspectstat(stat,what) /* no op */
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);
279 l_inspectstat(stat, what); /* interpret result */
280 if (*what == 'e' && stat == 0) /* successful termination? */
281 lua_pushboolean(L, 1);
284 lua_pushstring(L, what);
285 lua_pushinteger(L, stat);
286 return 3; /* return true/nil,what,code */
290 /* }====================================================== */
294 ** {======================================================
295 ** Userdata's metatable manipulation
296 ** =======================================================
299 LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
300 if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
301 return 0; /* leave previous value on top, but return 0 */
303 lua_createtable(L, 0, 2); /* create metatable */
304 lua_pushstring(L, tname);
305 lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
306 lua_pushvalue(L, -1);
307 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
312 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
313 luaL_getmetatable(L, tname);
314 lua_setmetatable(L, -2);
318 LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
319 void *p = lua_touserdata(L, ud);
320 if (p != NULL) { /* value is a userdata? */
321 if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
322 luaL_getmetatable(L, tname); /* get correct metatable */
323 if (!lua_rawequal(L, -1, -2)) /* not the same? */
324 p = NULL; /* value is a userdata with wrong metatable */
325 lua_pop(L, 2); /* remove both metatables */
329 return NULL; /* value is not a userdata with a metatable */
333 LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
334 void *p = luaL_testudata(L, ud, tname);
335 if (p == NULL) typeerror(L, ud, tname);
339 /* }====================================================== */
343 ** {======================================================
344 ** Argument check functions
345 ** =======================================================
348 LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
349 const char *const lst[]) {
350 const char *name = (def) ? luaL_optstring(L, arg, def) :
351 luaL_checkstring(L, arg);
353 for (i=0; lst[i]; i++)
354 if (strcmp(lst[i], name) == 0)
356 return luaL_argerror(L, arg,
357 lua_pushfstring(L, "invalid option '%s'", name));
362 ** Ensures the stack has at least 'space' extra slots, raising an error
363 ** if it cannot fulfill the request. (The error handling needs a few
364 ** extra slots to format the error message. In case of an error without
365 ** this extra space, Lua will generate the same 'stack overflow' error,
366 ** but without 'msg'.)
368 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
369 if (!lua_checkstack(L, space)) {
371 luaL_error(L, "stack overflow (%s)", msg);
373 luaL_error(L, "stack overflow");
378 LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
379 if (lua_type(L, arg) != t)
380 tag_error(L, arg, t);
384 LUALIB_API void luaL_checkany (lua_State *L, int arg) {
385 if (lua_type(L, arg) == LUA_TNONE)
386 luaL_argerror(L, arg, "value expected");
390 LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
391 const char *s = lua_tolstring(L, arg, len);
392 if (!s) tag_error(L, arg, LUA_TSTRING);
397 LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
398 const char *def, size_t *len) {
399 if (lua_isnoneornil(L, arg)) {
401 *len = (def ? strlen(def) : 0);
404 else return luaL_checklstring(L, arg, len);
408 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
410 lua_Number d = lua_tonumberx(L, arg, &isnum);
412 tag_error(L, arg, LUA_TNUMBER);
417 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
418 return luaL_opt(L, luaL_checknumber, arg, def);
422 static void interror (lua_State *L, int arg) {
423 if (lua_isnumber(L, arg))
424 luaL_argerror(L, arg, "number has no integer representation");
426 tag_error(L, arg, LUA_TNUMBER);
430 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
432 lua_Integer d = lua_tointegerx(L, arg, &isnum);
440 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
442 return luaL_opt(L, luaL_checkinteger, arg, def);
445 /* }====================================================== */
449 ** {======================================================
450 ** Generic Buffer manipulation
451 ** =======================================================
454 /* userdata to box arbitrary data */
455 typedef struct UBox {
461 static void *resizebox (lua_State *L, int idx, size_t newsize) {
463 lua_Alloc allocf = lua_getallocf(L, &ud);
464 UBox *box = (UBox *)lua_touserdata(L, idx);
465 void *temp = allocf(ud, box->box, box->bsize, newsize);
466 if (temp == NULL && newsize > 0) { /* allocation error? */
467 resizebox(L, idx, 0); /* free buffer */
468 luaL_error(L, "not enough memory for buffer allocation");
471 box->bsize = newsize;
476 static int boxgc (lua_State *L) {
482 static void *newbox (lua_State *L, size_t newsize) {
483 UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));
486 if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */
487 lua_pushcfunction(L, boxgc);
488 lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */
490 lua_setmetatable(L, -2);
491 return resizebox(L, -1, newsize);
496 ** check whether buffer is using a userdata on the stack as a temporary
499 #define buffonstack(B) ((B)->b != (B)->initb)
503 ** returns a pointer to a free area with at least 'sz' bytes
505 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
507 if (B->size - B->n < sz) { /* not enough space? */
509 size_t newsize = B->size * 2; /* double buffer size */
510 if (newsize - B->n < sz) /* not big enough? */
512 if (newsize < B->n || newsize - B->n < sz)
513 luaL_error(L, "buffer too large");
514 /* create larger buffer */
516 newbuff = (char *)resizebox(L, -1, newsize);
517 else { /* no buffer yet */
518 newbuff = (char *)newbox(L, newsize);
519 memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
528 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
529 if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
530 char *b = luaL_prepbuffsize(B, l);
531 memcpy(b, s, l * sizeof(char));
537 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
538 luaL_addlstring(B, s, strlen(s));
542 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
544 lua_pushlstring(L, B->b, B->n);
545 if (buffonstack(B)) {
546 resizebox(L, -2, 0); /* delete old buffer */
547 lua_remove(L, -2); /* remove its header from the stack */
552 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
558 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
561 const char *s = lua_tolstring(L, -1, &l);
563 lua_insert(L, -2); /* put value below buffer */
564 luaL_addlstring(B, s, l);
565 lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
569 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
573 B->size = LUAL_BUFFERSIZE;
577 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
579 return luaL_prepbuffsize(B, sz);
582 /* }====================================================== */
586 ** {======================================================
588 ** =======================================================
591 /* index of free-list header */
595 LUALIB_API int luaL_ref (lua_State *L, int t) {
597 if (lua_isnil(L, -1)) {
598 lua_pop(L, 1); /* remove from stack */
599 return LUA_REFNIL; /* 'nil' has a unique fixed reference */
601 t = lua_absindex(L, t);
602 lua_rawgeti(L, t, freelist); /* get first free element */
603 ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
604 lua_pop(L, 1); /* remove it from stack */
605 if (ref != 0) { /* any free element? */
606 lua_rawgeti(L, t, ref); /* remove it from list */
607 lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
609 else /* no free elements */
610 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
611 lua_rawseti(L, t, ref);
616 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
618 t = lua_absindex(L, t);
619 lua_rawgeti(L, t, freelist);
620 lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
621 lua_pushinteger(L, ref);
622 lua_rawseti(L, t, freelist); /* t[freelist] = ref */
626 /* }====================================================== */
630 ** {======================================================
632 ** =======================================================
635 typedef struct LoadF {
636 int n; /* number of pre-read characters */
637 FILE *f; /* file being read */
638 char buff[BUFSIZ]; /* area for reading file */
642 static const char *getF (lua_State *L, void *ud, size_t *size) {
643 LoadF *lf = (LoadF *)ud;
644 (void)L; /* not used */
645 if (lf->n > 0) { /* are there pre-read characters to be read? */
646 *size = lf->n; /* return them (chars already in buffer) */
647 lf->n = 0; /* no more pre-read characters */
649 else { /* read a block from file */
650 /* 'fread' can return > 0 *and* set the EOF flag. If next call to
651 'getF' called 'fread', it might still wait for user input.
652 The next check avoids this problem. */
653 if (feof(lf->f)) return NULL;
654 *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
660 static int errfile (lua_State *L, const char *what, int fnameindex) {
661 const char *serr = strerror(errno);
662 const char *filename = lua_tostring(L, fnameindex) + 1;
663 lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
664 lua_remove(L, fnameindex);
669 static int skipBOM (LoadF *lf) {
670 const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
675 if (c == EOF || c != *(const unsigned char *)p++) return c;
676 lf->buff[lf->n++] = c; /* to be read by the parser */
677 } while (*p != '\0');
678 lf->n = 0; /* prefix matched; discard it */
679 return getc(lf->f); /* return next character */
684 ** reads the first character of file 'f' and skips an optional BOM mark
685 ** in its beginning plus its first line if it starts with '#'. Returns
686 ** true if it skipped the first line. In any case, '*cp' has the
687 ** first "valid" character of the file (after the optional BOM and
688 ** a first-line comment).
690 static int skipcomment (LoadF *lf, int *cp) {
691 int c = *cp = skipBOM(lf);
692 if (c == '#') { /* first line is a comment (Unix exec. file)? */
693 do { /* skip first line */
695 } while (c != EOF && c != '\n');
696 *cp = getc(lf->f); /* skip end-of-line, if present */
697 return 1; /* there was a comment */
699 else return 0; /* no comment */
703 LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
706 int status, readstatus;
708 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
709 if (filename == NULL) {
710 lua_pushliteral(L, "=stdin");
714 lua_pushfstring(L, "@%s", filename);
715 lf.f = fopen(filename, "r");
716 if (lf.f == NULL) return errfile(L, "open", fnameindex);
718 if (skipcomment(&lf, &c)) /* read initial portion */
719 lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
720 if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
721 lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
722 if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
723 skipcomment(&lf, &c); /* re-read initial portion */
726 lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
727 status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
728 readstatus = ferror(lf.f);
729 if (filename) fclose(lf.f); /* close file (even in case of errors) */
731 lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
732 return errfile(L, "read", fnameindex);
734 lua_remove(L, fnameindex);
739 typedef struct LoadS {
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;
755 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
756 const char *name, const char *mode) {
760 return lua_load(L, getS, &ls, name, mode);
764 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
765 return luaL_loadbuffer(L, s, strlen(s), s);
768 /* }====================================================== */
772 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
773 if (!lua_getmetatable(L, obj)) /* no metatable? */
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 */
782 lua_remove(L, -2); /* remove only metatable */
783 return tt; /* return metafield type */
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? */
792 lua_pushvalue(L, obj);
798 LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
802 l = lua_tointegerx(L, -1, &isnum);
804 luaL_error(L, "object length is not an integer");
805 lua_pop(L, 1); /* remove object */
810 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
811 if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
812 if (!lua_isstring(L, -1))
813 luaL_error(L, "'__tostring' must return a string");
816 switch (lua_type(L, idx)) {
818 if (lua_isinteger(L, idx))
819 lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
821 lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
825 lua_pushvalue(L, idx);
828 lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
831 lua_pushliteral(L, "nil");
834 int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
835 const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
836 luaL_typename(L, idx);
837 lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
839 lua_remove(L, -2); /* remove '__name' */
844 return lua_tolstring(L, -1, len);
849 ** {======================================================
850 ** Compatibility with 5.1 module functions
851 ** =======================================================
853 #if defined(LUA_COMPAT_MODULE)
855 static const char *luaL_findtable (lua_State *L, int idx,
856 const char *fname, int szhint) {
858 if (idx) lua_pushvalue(L, idx);
860 e = strchr(fname, '.');
861 if (e == NULL) e = fname + strlen(fname);
862 lua_pushlstring(L, fname, e - fname);
863 if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
864 lua_pop(L, 1); /* remove this nil */
865 lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
866 lua_pushlstring(L, fname, e - fname);
867 lua_pushvalue(L, -2);
868 lua_settable(L, -4); /* set new table into field */
870 else if (!lua_istable(L, -1)) { /* field has a non-table value? */
871 lua_pop(L, 2); /* remove table and value */
872 return fname; /* return problematic part of the name */
874 lua_remove(L, -2); /* remove previous table */
882 ** Count number of elements in a luaL_Reg list.
884 static int libsize (const luaL_Reg *l) {
886 for (; l && l->name; l++) size++;
892 ** Find or create a module table with a given name. The function
893 ** first looks at the LOADED table and, if that fails, try a
894 ** global variable with that name. In any case, leaves on the stack
897 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
899 luaL_findtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE, 1);
900 if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no LOADED[modname]? */
901 lua_pop(L, 1); /* remove previous result */
902 /* try global variable (and create one if it does not exist) */
903 lua_pushglobaltable(L);
904 if (luaL_findtable(L, 0, modname, sizehint) != NULL)
905 luaL_error(L, "name conflict for module '%s'", modname);
906 lua_pushvalue(L, -1);
907 lua_setfield(L, -3, modname); /* LOADED[modname] = new table */
909 lua_remove(L, -2); /* remove LOADED table */
913 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
914 const luaL_Reg *l, int nup) {
915 luaL_checkversion(L);
917 luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
918 lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
921 luaL_setfuncs(L, l, nup);
923 lua_pop(L, nup); /* remove upvalues */
927 /* }====================================================== */
930 ** set functions from list 'l' into table at top - 'nup'; each
931 ** function gets the 'nup' elements at the top as upvalues.
932 ** Returns with only the table at the stack.
934 LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
935 luaL_checkstack(L, nup, "too many upvalues");
936 for (; l->name != NULL; l++) { /* fill the table with given functions */
938 for (i = 0; i < nup; i++) /* copy upvalues to the top */
939 lua_pushvalue(L, -nup);
940 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
941 lua_setfield(L, -(nup + 2), l->name);
943 lua_pop(L, nup); /* remove upvalues */
948 ** ensure that stack[idx][fname] has a table and push that table
951 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
952 if (lua_getfield(L, idx, fname) == LUA_TTABLE)
953 return 1; /* table already there */
955 lua_pop(L, 1); /* remove previous result */
956 idx = lua_absindex(L, idx);
958 lua_pushvalue(L, -1); /* copy to be left at top */
959 lua_setfield(L, idx, fname); /* assign new table to field */
960 return 0; /* false, because did not find table there */
966 ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
967 ** to open a module, registers the result in 'package.loaded' table and,
968 ** if 'glb' is true, also registers the result in the global table.
969 ** Leaves resulting module on the top.
971 LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
972 lua_CFunction openf, int glb) {
973 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
974 lua_getfield(L, -1, modname); /* LOADED[modname] */
975 if (!lua_toboolean(L, -1)) { /* package not already loaded? */
976 lua_pop(L, 1); /* remove field */
977 lua_pushcfunction(L, openf);
978 lua_pushstring(L, modname); /* argument to open function */
979 lua_call(L, 1, 1); /* call 'openf' to open module */
980 lua_pushvalue(L, -1); /* make copy of module (call result) */
981 lua_setfield(L, -3, modname); /* LOADED[modname] = module */
983 lua_remove(L, -2); /* remove LOADED table */
985 lua_pushvalue(L, -1); /* copy of module */
986 lua_setglobal(L, modname); /* _G[modname] = module */
991 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
994 size_t l = strlen(p);
996 luaL_buffinit(L, &b);
997 while ((wild = strstr(s, p)) != NULL) {
998 luaL_addlstring(&b, s, wild - s); /* push prefix */
999 luaL_addstring(&b, r); /* push replacement in place of pattern */
1000 s = wild + l; /* continue after 'p' */
1002 luaL_addstring(&b, s); /* push last suffix */
1003 luaL_pushresult(&b);
1004 return lua_tostring(L, -1);
1008 static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1009 (void)ud; (void)osize; /* not used */
1014 else { /* cannot fail when shrinking a block */
1015 void *newptr = realloc(ptr, nsize);
1016 if (newptr == NULL && ptr != NULL && nsize <= osize)
1017 return ptr; /* keep the original block */
1018 else /* no fail or not shrinking */
1019 return newptr; /* use the new block */
1024 static int panic (lua_State *L) {
1025 lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
1026 lua_tostring(L, -1));
1027 return 0; /* return to Lua to abort */
1031 LUALIB_API lua_State *luaL_newstate (void) {
1032 lua_State *L = lua_newstate(l_alloc, NULL);
1033 if (L) lua_atpanic(L, &panic);
1038 LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
1039 const lua_Number *v = lua_version(L);
1040 if (sz != LUAL_NUMSIZES) /* check numeric types */
1041 luaL_error(L, "core and library have incompatible numeric types");
1042 if (v != lua_version(NULL))
1043 luaL_error(L, "multiple Lua VMs detected");
1045 luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
1046 (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)*v);