2 ** $Id: lauxlib.c,v 1.284 2015/11/19 19:16:22 roberto Exp $
3 ** Auxiliary functions for building Lua libraries
4 ** See Copyright Notice in lua.h
20 /* This file uses only the official API of Lua.
21 ** Any function declared here could be written as an application function.
30 ** {======================================================
32 ** =======================================================
36 #define LEVELS1 10 /* size of the first part of the stack */
37 #define LEVELS2 11 /* size of the second part of the stack */
42 ** search for 'objidx' in table at index -1.
43 ** return 1 + string at top if find a good name.
45 static int findfield (lua_State *L, int objidx, int level) {
46 if (level == 0 || !lua_istable(L, -1))
47 return 0; /* not found */
48 lua_pushnil(L); /* start 'next' loop */
49 while (lua_next(L, -2)) { /* for each pair in table */
50 if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
51 if (lua_rawequal(L, objidx, -1)) { /* found object? */
52 lua_pop(L, 1); /* remove value (but keep name) */
55 else if (findfield(L, objidx, level - 1)) { /* try recursively */
56 lua_remove(L, -2); /* remove table (but keep name) */
57 lua_pushliteral(L, ".");
58 lua_insert(L, -2); /* place '.' between the two names */
63 lua_pop(L, 1); /* remove value */
65 return 0; /* not found */
70 ** Search for a name for a function in all loaded modules
71 ** (registry._LOADED).
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, "_LOADED");
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));
201 LUALIB_API void luaL_where (lua_State *L, int level) {
203 if (lua_getstack(L, level, &ar)) { /* check function at level */
204 lua_getinfo(L, "Sl", &ar); /* get info about it */
205 if (ar.currentline > 0) { /* is there info? */
206 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
210 lua_pushliteral(L, ""); /* else, no information available... */
214 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
218 lua_pushvfstring(L, fmt, argp);
225 LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
226 int en = errno; /* calls to Lua API may change this value */
228 lua_pushboolean(L, 1);
234 lua_pushfstring(L, "%s: %s", fname, strerror(en));
236 lua_pushstring(L, strerror(en));
237 lua_pushinteger(L, en);
243 #if !defined(l_inspectstat) /* { */
245 #if defined(LUA_USE_POSIX)
247 #include <sys/wait.h>
250 ** use appropriate macros to interpret 'pclose' return status
252 #define l_inspectstat(stat,what) \
253 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
254 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
258 #define l_inspectstat(stat,what) /* no op */
265 LUALIB_API int luaL_execresult (lua_State *L, int stat) {
266 const char *what = "exit"; /* type of termination */
267 if (stat == -1) /* error? */
268 return luaL_fileresult(L, 0, NULL);
270 l_inspectstat(stat, what); /* interpret result */
271 if (*what == 'e' && stat == 0) /* successful termination? */
272 lua_pushboolean(L, 1);
275 lua_pushstring(L, what);
276 lua_pushinteger(L, stat);
277 return 3; /* return true/nil,what,code */
281 /* }====================================================== */
285 ** {======================================================
286 ** Userdata's metatable manipulation
287 ** =======================================================
290 LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
291 if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
292 return 0; /* leave previous value on top, but return 0 */
294 lua_createtable(L, 0, 2); /* create metatable */
295 lua_pushstring(L, tname);
296 lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
297 lua_pushvalue(L, -1);
298 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
303 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
304 luaL_getmetatable(L, tname);
305 lua_setmetatable(L, -2);
309 LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
310 void *p = lua_touserdata(L, ud);
311 if (p != NULL) { /* value is a userdata? */
312 if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
313 luaL_getmetatable(L, tname); /* get correct metatable */
314 if (!lua_rawequal(L, -1, -2)) /* not the same? */
315 p = NULL; /* value is a userdata with wrong metatable */
316 lua_pop(L, 2); /* remove both metatables */
320 return NULL; /* value is not a userdata with a metatable */
324 LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
325 void *p = luaL_testudata(L, ud, tname);
326 if (p == NULL) typeerror(L, ud, tname);
330 /* }====================================================== */
334 ** {======================================================
335 ** Argument check functions
336 ** =======================================================
339 LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
340 const char *const lst[]) {
341 const char *name = (def) ? luaL_optstring(L, arg, def) :
342 luaL_checkstring(L, arg);
344 for (i=0; lst[i]; i++)
345 if (strcmp(lst[i], name) == 0)
347 return luaL_argerror(L, arg,
348 lua_pushfstring(L, "invalid option '%s'", name));
352 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
353 /* keep some extra space to run error routines, if needed */
354 const int extra = LUA_MINSTACK;
355 if (!lua_checkstack(L, space + extra)) {
357 luaL_error(L, "stack overflow (%s)", msg);
359 luaL_error(L, "stack overflow");
364 LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
365 if (lua_type(L, arg) != t)
366 tag_error(L, arg, t);
370 LUALIB_API void luaL_checkany (lua_State *L, int arg) {
371 if (lua_type(L, arg) == LUA_TNONE)
372 luaL_argerror(L, arg, "value expected");
376 LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
377 const char *s = lua_tolstring(L, arg, len);
378 if (!s) tag_error(L, arg, LUA_TSTRING);
383 LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
384 const char *def, size_t *len) {
385 if (lua_isnoneornil(L, arg)) {
387 *len = (def ? strlen(def) : 0);
390 else return luaL_checklstring(L, arg, len);
394 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
396 lua_Number d = lua_tonumberx(L, arg, &isnum);
398 tag_error(L, arg, LUA_TNUMBER);
403 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
404 return luaL_opt(L, luaL_checknumber, arg, def);
408 static void interror (lua_State *L, int arg) {
409 if (lua_isnumber(L, arg))
410 luaL_argerror(L, arg, "number has no integer representation");
412 tag_error(L, arg, LUA_TNUMBER);
416 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
418 lua_Integer d = lua_tointegerx(L, arg, &isnum);
426 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
428 return luaL_opt(L, luaL_checkinteger, arg, def);
431 /* }====================================================== */
435 ** {======================================================
436 ** Generic Buffer manipulation
437 ** =======================================================
440 /* userdata to box arbitrary data */
441 typedef struct UBox {
447 static void *resizebox (lua_State *L, int idx, size_t newsize) {
449 lua_Alloc allocf = lua_getallocf(L, &ud);
450 UBox *box = (UBox *)lua_touserdata(L, idx);
451 void *temp = allocf(ud, box->box, box->bsize, newsize);
452 if (temp == NULL && newsize > 0) { /* allocation error? */
453 resizebox(L, idx, 0); /* free buffer */
454 luaL_error(L, "not enough memory for buffer allocation");
457 box->bsize = newsize;
462 static int boxgc (lua_State *L) {
468 static void *newbox (lua_State *L, size_t newsize) {
469 UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));
472 if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */
473 lua_pushcfunction(L, boxgc);
474 lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */
476 lua_setmetatable(L, -2);
477 return resizebox(L, -1, newsize);
482 ** check whether buffer is using a userdata on the stack as a temporary
485 #define buffonstack(B) ((B)->b != (B)->initb)
489 ** returns a pointer to a free area with at least 'sz' bytes
491 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
493 if (B->size - B->n < sz) { /* not enough space? */
495 size_t newsize = B->size * 2; /* double buffer size */
496 if (newsize - B->n < sz) /* not big enough? */
498 if (newsize < B->n || newsize - B->n < sz)
499 luaL_error(L, "buffer too large");
500 /* create larger buffer */
502 newbuff = (char *)resizebox(L, -1, newsize);
503 else { /* no buffer yet */
504 newbuff = (char *)newbox(L, newsize);
505 memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
514 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
515 if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
516 char *b = luaL_prepbuffsize(B, l);
517 memcpy(b, s, l * sizeof(char));
523 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
524 luaL_addlstring(B, s, strlen(s));
528 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
530 lua_pushlstring(L, B->b, B->n);
531 if (buffonstack(B)) {
532 resizebox(L, -2, 0); /* delete old buffer */
533 lua_remove(L, -2); /* remove its header from the stack */
538 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
544 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
547 const char *s = lua_tolstring(L, -1, &l);
549 lua_insert(L, -2); /* put value below buffer */
550 luaL_addlstring(B, s, l);
551 lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
555 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
559 B->size = LUAL_BUFFERSIZE;
563 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
565 return luaL_prepbuffsize(B, sz);
568 /* }====================================================== */
572 ** {======================================================
574 ** =======================================================
577 /* index of free-list header */
581 LUALIB_API int luaL_ref (lua_State *L, int t) {
583 if (lua_isnil(L, -1)) {
584 lua_pop(L, 1); /* remove from stack */
585 return LUA_REFNIL; /* 'nil' has a unique fixed reference */
587 t = lua_absindex(L, t);
588 lua_rawgeti(L, t, freelist); /* get first free element */
589 ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
590 lua_pop(L, 1); /* remove it from stack */
591 if (ref != 0) { /* any free element? */
592 lua_rawgeti(L, t, ref); /* remove it from list */
593 lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
595 else /* no free elements */
596 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
597 lua_rawseti(L, t, ref);
602 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
604 t = lua_absindex(L, t);
605 lua_rawgeti(L, t, freelist);
606 lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
607 lua_pushinteger(L, ref);
608 lua_rawseti(L, t, freelist); /* t[freelist] = ref */
612 /* }====================================================== */
616 ** {======================================================
618 ** =======================================================
621 typedef struct LoadF {
622 int n; /* number of pre-read characters */
623 FILE *f; /* file being read */
624 char buff[BUFSIZ]; /* area for reading file */
628 static const char *getF (lua_State *L, void *ud, size_t *size) {
629 LoadF *lf = (LoadF *)ud;
630 (void)L; /* not used */
631 if (lf->n > 0) { /* are there pre-read characters to be read? */
632 *size = lf->n; /* return them (chars already in buffer) */
633 lf->n = 0; /* no more pre-read characters */
635 else { /* read a block from file */
636 /* 'fread' can return > 0 *and* set the EOF flag. If next call to
637 'getF' called 'fread', it might still wait for user input.
638 The next check avoids this problem. */
639 if (feof(lf->f)) return NULL;
640 *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
646 static int errfile (lua_State *L, const char *what, int fnameindex) {
647 const char *serr = strerror(errno);
648 const char *filename = lua_tostring(L, fnameindex) + 1;
649 lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
650 lua_remove(L, fnameindex);
655 static int skipBOM (LoadF *lf) {
656 const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
661 if (c == EOF || c != *(const unsigned char *)p++) return c;
662 lf->buff[lf->n++] = c; /* to be read by the parser */
663 } while (*p != '\0');
664 lf->n = 0; /* prefix matched; discard it */
665 return getc(lf->f); /* return next character */
670 ** reads the first character of file 'f' and skips an optional BOM mark
671 ** in its beginning plus its first line if it starts with '#'. Returns
672 ** true if it skipped the first line. In any case, '*cp' has the
673 ** first "valid" character of the file (after the optional BOM and
674 ** a first-line comment).
676 static int skipcomment (LoadF *lf, int *cp) {
677 int c = *cp = skipBOM(lf);
678 if (c == '#') { /* first line is a comment (Unix exec. file)? */
679 do { /* skip first line */
681 } while (c != EOF && c != '\n') ;
682 *cp = getc(lf->f); /* skip end-of-line, if present */
683 return 1; /* there was a comment */
685 else return 0; /* no comment */
689 LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
692 int status, readstatus;
694 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
695 if (filename == NULL) {
696 lua_pushliteral(L, "=stdin");
700 lua_pushfstring(L, "@%s", filename);
701 lf.f = fopen(filename, "r");
702 if (lf.f == NULL) return errfile(L, "open", fnameindex);
704 if (skipcomment(&lf, &c)) /* read initial portion */
705 lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
706 if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
707 lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
708 if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
709 skipcomment(&lf, &c); /* re-read initial portion */
712 lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
713 status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
714 readstatus = ferror(lf.f);
715 if (filename) fclose(lf.f); /* close file (even in case of errors) */
717 lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
718 return errfile(L, "read", fnameindex);
720 lua_remove(L, fnameindex);
725 typedef struct LoadS {
731 static const char *getS (lua_State *L, void *ud, size_t *size) {
732 LoadS *ls = (LoadS *)ud;
733 (void)L; /* not used */
734 if (ls->size == 0) return NULL;
741 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
742 const char *name, const char *mode) {
746 return lua_load(L, getS, &ls, name, mode);
750 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
751 return luaL_loadbuffer(L, s, strlen(s), s);
754 /* }====================================================== */
758 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
759 if (!lua_getmetatable(L, obj)) /* no metatable? */
763 lua_pushstring(L, event);
764 tt = lua_rawget(L, -2);
765 if (tt == LUA_TNIL) /* is metafield nil? */
766 lua_pop(L, 2); /* remove metatable and metafield */
768 lua_remove(L, -2); /* remove only metatable */
769 return tt; /* return metafield type */
774 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
775 obj = lua_absindex(L, obj);
776 if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
778 lua_pushvalue(L, obj);
784 LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
788 l = lua_tointegerx(L, -1, &isnum);
790 luaL_error(L, "object length is not an integer");
791 lua_pop(L, 1); /* remove object */
796 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
797 if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
798 switch (lua_type(L, idx)) {
800 if (lua_isinteger(L, idx))
801 lua_pushfstring(L, "%I", lua_tointeger(L, idx));
803 lua_pushfstring(L, "%f", lua_tonumber(L, idx));
807 lua_pushvalue(L, idx);
810 lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
813 lua_pushliteral(L, "nil");
816 lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
817 lua_topointer(L, idx));
821 return lua_tolstring(L, -1, len);
826 ** {======================================================
827 ** Compatibility with 5.1 module functions
828 ** =======================================================
830 #if defined(LUA_COMPAT_MODULE)
832 static const char *luaL_findtable (lua_State *L, int idx,
833 const char *fname, int szhint) {
835 if (idx) lua_pushvalue(L, idx);
837 e = strchr(fname, '.');
838 if (e == NULL) e = fname + strlen(fname);
839 lua_pushlstring(L, fname, e - fname);
840 if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
841 lua_pop(L, 1); /* remove this nil */
842 lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
843 lua_pushlstring(L, fname, e - fname);
844 lua_pushvalue(L, -2);
845 lua_settable(L, -4); /* set new table into field */
847 else if (!lua_istable(L, -1)) { /* field has a non-table value? */
848 lua_pop(L, 2); /* remove table and value */
849 return fname; /* return problematic part of the name */
851 lua_remove(L, -2); /* remove previous table */
859 ** Count number of elements in a luaL_Reg list.
861 static int libsize (const luaL_Reg *l) {
863 for (; l && l->name; l++) size++;
869 ** Find or create a module table with a given name. The function
870 ** first looks at the _LOADED table and, if that fails, try a
871 ** global variable with that name. In any case, leaves on the stack
874 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
876 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
877 if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no _LOADED[modname]? */
878 lua_pop(L, 1); /* remove previous result */
879 /* try global variable (and create one if it does not exist) */
880 lua_pushglobaltable(L);
881 if (luaL_findtable(L, 0, modname, sizehint) != NULL)
882 luaL_error(L, "name conflict for module '%s'", modname);
883 lua_pushvalue(L, -1);
884 lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
886 lua_remove(L, -2); /* remove _LOADED table */
890 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
891 const luaL_Reg *l, int nup) {
892 luaL_checkversion(L);
894 luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
895 lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
898 luaL_setfuncs(L, l, nup);
900 lua_pop(L, nup); /* remove upvalues */
904 /* }====================================================== */
907 ** set functions from list 'l' into table at top - 'nup'; each
908 ** function gets the 'nup' elements at the top as upvalues.
909 ** Returns with only the table at the stack.
911 LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
912 luaL_checkstack(L, nup, "too many upvalues");
913 for (; l->name != NULL; l++) { /* fill the table with given functions */
915 for (i = 0; i < nup; i++) /* copy upvalues to the top */
916 lua_pushvalue(L, -nup);
917 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
918 lua_setfield(L, -(nup + 2), l->name);
920 lua_pop(L, nup); /* remove upvalues */
925 ** ensure that stack[idx][fname] has a table and push that table
928 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
929 if (lua_getfield(L, idx, fname) == LUA_TTABLE)
930 return 1; /* table already there */
932 lua_pop(L, 1); /* remove previous result */
933 idx = lua_absindex(L, idx);
935 lua_pushvalue(L, -1); /* copy to be left at top */
936 lua_setfield(L, idx, fname); /* assign new table to field */
937 return 0; /* false, because did not find table there */
943 ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
944 ** to open a module, registers the result in 'package.loaded' table and,
945 ** if 'glb' is true, also registers the result in the global table.
946 ** Leaves resulting module on the top.
948 LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
949 lua_CFunction openf, int glb) {
950 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
951 lua_getfield(L, -1, modname); /* _LOADED[modname] */
952 if (!lua_toboolean(L, -1)) { /* package not already loaded? */
953 lua_pop(L, 1); /* remove field */
954 lua_pushcfunction(L, openf);
955 lua_pushstring(L, modname); /* argument to open function */
956 lua_call(L, 1, 1); /* call 'openf' to open module */
957 lua_pushvalue(L, -1); /* make copy of module (call result) */
958 lua_setfield(L, -3, modname); /* _LOADED[modname] = module */
960 lua_remove(L, -2); /* remove _LOADED table */
962 lua_pushvalue(L, -1); /* copy of module */
963 lua_setglobal(L, modname); /* _G[modname] = module */
968 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
971 size_t l = strlen(p);
973 luaL_buffinit(L, &b);
974 while ((wild = strstr(s, p)) != NULL) {
975 luaL_addlstring(&b, s, wild - s); /* push prefix */
976 luaL_addstring(&b, r); /* push replacement in place of pattern */
977 s = wild + l; /* continue after 'p' */
979 luaL_addstring(&b, s); /* push last suffix */
981 return lua_tostring(L, -1);
985 static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
986 (void)ud; (void)osize; /* not used */
992 return realloc(ptr, nsize);
996 static int panic (lua_State *L) {
997 lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
998 lua_tostring(L, -1));
999 return 0; /* return to Lua to abort */
1003 LUALIB_API lua_State *luaL_newstate (void) {
1004 lua_State *L = lua_newstate(l_alloc, NULL);
1005 if (L) lua_atpanic(L, &panic);
1010 LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
1011 const lua_Number *v = lua_version(L);
1012 if (sz != LUAL_NUMSIZES) /* check numeric types */
1013 luaL_error(L, "core and library have incompatible numeric types");
1014 if (v != lua_version(NULL))
1015 luaL_error(L, "multiple Lua VMs detected");
1017 luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",