1 /* $NetBSD: lauxlib.c,v 1.5 2015/10/08 13:21:00 mbalmer Exp $ */
4 ** Id: lauxlib.c,v 1.280 2015/02/03 17:38:24 roberto Exp
5 ** Auxiliary functions for building Lua libraries
6 ** See Copyright Notice in lua.h
26 /* This file uses only the official API of Lua.
27 ** Any function declared here could be written as an application function.
36 ** {======================================================
38 ** =======================================================
42 #define LEVELS1 12 /* size of the first part of the stack */
43 #define LEVELS2 10 /* size of the second part of the stack */
48 ** search for 'objidx' in table at index -1.
49 ** return 1 + string at top if find a good name.
51 static int findfield (lua_State
*L
, int objidx
, int level
) {
52 if (level
== 0 || !lua_istable(L
, -1))
53 return 0; /* not found */
54 lua_pushnil(L
); /* start 'next' loop */
55 while (lua_next(L
, -2)) { /* for each pair in table */
56 if (lua_type(L
, -2) == LUA_TSTRING
) { /* ignore non-string keys */
57 if (lua_rawequal(L
, objidx
, -1)) { /* found object? */
58 lua_pop(L
, 1); /* remove value (but keep name) */
61 else if (findfield(L
, objidx
, level
- 1)) { /* try recursively */
62 lua_remove(L
, -2); /* remove table (but keep name) */
63 lua_pushliteral(L
, ".");
64 lua_insert(L
, -2); /* place '.' between the two names */
69 lua_pop(L
, 1); /* remove value */
71 return 0; /* not found */
76 ** Search for a name for a function in all loaded modules
77 ** (registry._LOADED).
79 static int pushglobalfuncname (lua_State
*L
, lua_Debug
*ar
) {
80 int top
= lua_gettop(L
);
81 lua_getinfo(L
, "f", ar
); /* push function */
82 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
83 if (findfield(L
, top
+ 1, 2)) {
84 const char *name
= lua_tostring(L
, -1);
85 if (strncmp(name
, "_G.", 3) == 0) { /* name start with '_G.'? */
86 lua_pushstring(L
, name
+ 3); /* push name without prefix */
87 lua_remove(L
, -2); /* remove original name */
89 lua_copy(L
, -1, top
+ 1); /* move name to proper place */
90 lua_pop(L
, 2); /* remove pushed values */
94 lua_settop(L
, top
); /* remove function and global table */
100 static void pushfuncname (lua_State
*L
, lua_Debug
*ar
) {
101 if (pushglobalfuncname(L
, ar
)) { /* try first a global name */
102 lua_pushfstring(L
, "function '%s'", lua_tostring(L
, -1));
103 lua_remove(L
, -2); /* remove name */
105 else if (*ar
->namewhat
!= '\0') /* is there a name from code? */
106 lua_pushfstring(L
, "%s '%s'", ar
->namewhat
, ar
->name
); /* use it */
107 else if (*ar
->what
== 'm') /* main? */
108 lua_pushliteral(L
, "main chunk");
109 else if (*ar
->what
!= 'C') /* for Lua functions, use <file:line> */
110 lua_pushfstring(L
, "function <%s:%d>", ar
->short_src
, ar
->linedefined
);
111 else /* nothing left... */
112 lua_pushliteral(L
, "?");
116 static int countlevels (lua_State
*L
) {
119 /* find an upper bound */
120 while (lua_getstack(L
, le
, &ar
)) { li
= le
; le
*= 2; }
121 /* do a binary search */
124 if (lua_getstack(L
, m
, &ar
)) li
= m
+ 1;
131 LUALIB_API
void luaL_traceback (lua_State
*L
, lua_State
*L1
,
132 const char *msg
, int level
) {
134 int top
= lua_gettop(L
);
135 int numlevels
= countlevels(L1
);
136 int mark
= (numlevels
> LEVELS1
+ LEVELS2
) ? LEVELS1
: 0;
137 if (msg
) lua_pushfstring(L
, "%s\n", msg
);
138 lua_pushliteral(L
, "stack traceback:");
139 while (lua_getstack(L1
, level
++, &ar
)) {
140 if (level
== mark
) { /* too many levels? */
141 lua_pushliteral(L
, "\n\t..."); /* add a '...' */
142 level
= numlevels
- LEVELS2
; /* and skip to last ones */
145 lua_getinfo(L1
, "Slnt", &ar
);
146 lua_pushfstring(L
, "\n\t%s:", ar
.short_src
);
147 if (ar
.currentline
> 0)
148 lua_pushfstring(L
, "%d:", ar
.currentline
);
149 lua_pushliteral(L
, " in ");
150 pushfuncname(L
, &ar
);
152 lua_pushliteral(L
, "\n\t(...tail calls...)");
153 lua_concat(L
, lua_gettop(L
) - top
);
156 lua_concat(L
, lua_gettop(L
) - top
);
159 /* }====================================================== */
163 ** {======================================================
164 ** Error-report functions
165 ** =======================================================
168 LUALIB_API
int luaL_argerror (lua_State
*L
, int arg
, const char *extramsg
) {
170 if (!lua_getstack(L
, 0, &ar
)) /* no stack frame? */
171 return luaL_error(L
, "bad argument #%d (%s)", arg
, extramsg
);
172 lua_getinfo(L
, "n", &ar
);
173 if (strcmp(ar
.namewhat
, "method") == 0) {
174 arg
--; /* do not count 'self' */
175 if (arg
== 0) /* error is in the self argument itself? */
176 return luaL_error(L
, "calling '%s' on bad self (%s)",
180 ar
.name
= (pushglobalfuncname(L
, &ar
)) ? lua_tostring(L
, -1) : "?";
181 return luaL_error(L
, "bad argument #%d to '%s' (%s)",
182 arg
, ar
.name
, extramsg
);
186 static int typeerror (lua_State
*L
, int arg
, const char *tname
) {
188 const char *typearg
; /* name for the type of the actual argument */
189 if (luaL_getmetafield(L
, arg
, "__name") == LUA_TSTRING
)
190 typearg
= lua_tostring(L
, -1); /* use the given type name */
191 else if (lua_type(L
, arg
) == LUA_TLIGHTUSERDATA
)
192 typearg
= "light userdata"; /* special name for messages */
194 typearg
= luaL_typename(L
, arg
); /* standard name */
195 msg
= lua_pushfstring(L
, "%s expected, got %s", tname
, typearg
);
196 return luaL_argerror(L
, arg
, msg
);
200 static void tag_error (lua_State
*L
, int arg
, int tag
) {
201 typeerror(L
, arg
, lua_typename(L
, tag
));
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_pushliteral(L
, ""); /* else, no information available... */
218 LUALIB_API
int luaL_error (lua_State
*L
, const char *fmt
, ...) {
222 lua_pushvfstring(L
, fmt
, argp
);
230 LUALIB_API
int luaL_fileresult (lua_State
*L
, int stat
, const char *fname
) {
231 int en
= errno
; /* calls to Lua API may change this value */
233 lua_pushboolean(L
, 1);
239 lua_pushfstring(L
, "%s: %s", fname
, strerror(en
));
241 lua_pushstring(L
, strerror(en
));
242 lua_pushinteger(L
, en
);
249 #if !defined(l_inspectstat) /* { */
251 #if defined(LUA_USE_POSIX)
253 #include <sys/wait.h>
256 ** use appropriate macros to interpret 'pclose' return status
258 #define l_inspectstat(stat,what) \
259 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
260 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
264 #define l_inspectstat(stat,what) /* no op */
272 LUALIB_API
int luaL_execresult (lua_State
*L
, int stat
) {
273 const char *what
= "exit"; /* type of termination */
274 if (stat
== -1) /* error? */
275 return luaL_fileresult(L
, 0, NULL
);
277 l_inspectstat(stat
, what
); /* interpret result */
278 if (*what
== 'e' && stat
== 0) /* successful termination? */
279 lua_pushboolean(L
, 1);
282 lua_pushstring(L
, what
);
283 lua_pushinteger(L
, stat
);
284 return 3; /* return true/nil,what,code */
289 /* }====================================================== */
293 ** {======================================================
294 ** Userdata's metatable manipulation
295 ** =======================================================
298 LUALIB_API
int luaL_newmetatable (lua_State
*L
, const char *tname
) {
299 if (luaL_getmetatable(L
, tname
) != LUA_TNIL
) /* name already in use? */
300 return 0; /* leave previous value on top, but return 0 */
302 lua_newtable(L
); /* create metatable */
303 lua_pushstring(L
, tname
);
304 lua_setfield(L
, -2, "__name"); /* metatable.__name = tname */
305 lua_pushvalue(L
, -1);
306 lua_setfield(L
, LUA_REGISTRYINDEX
, tname
); /* registry.name = metatable */
311 LUALIB_API
void luaL_setmetatable (lua_State
*L
, const char *tname
) {
312 luaL_getmetatable(L
, tname
);
313 lua_setmetatable(L
, -2);
317 LUALIB_API
void *luaL_testudata (lua_State
*L
, int ud
, const char *tname
) {
318 void *p
= lua_touserdata(L
, ud
);
319 if (p
!= NULL
) { /* value is a userdata? */
320 if (lua_getmetatable(L
, ud
)) { /* does it have a metatable? */
321 luaL_getmetatable(L
, tname
); /* get correct metatable */
322 if (!lua_rawequal(L
, -1, -2)) /* not the same? */
323 p
= NULL
; /* value is a userdata with wrong metatable */
324 lua_pop(L
, 2); /* remove both metatables */
328 return NULL
; /* value is not a userdata with a metatable */
332 LUALIB_API
void *luaL_checkudata (lua_State
*L
, int ud
, const char *tname
) {
333 void *p
= luaL_testudata(L
, ud
, tname
);
334 if (p
== NULL
) typeerror(L
, ud
, tname
);
338 /* }====================================================== */
342 ** {======================================================
343 ** Argument check functions
344 ** =======================================================
347 LUALIB_API
int luaL_checkoption (lua_State
*L
, int arg
, const char *def
,
348 const char *const lst
[]) {
349 const char *name
= (def
) ? luaL_optstring(L
, arg
, def
) :
350 luaL_checkstring(L
, arg
);
352 for (i
=0; lst
[i
]; i
++)
353 if (strcmp(lst
[i
], name
) == 0)
355 return luaL_argerror(L
, arg
,
356 lua_pushfstring(L
, "invalid option '%s'", name
));
360 LUALIB_API
void luaL_checkstack (lua_State
*L
, int space
, const char *msg
) {
361 /* keep some extra space to run error routines, if needed */
362 const int extra
= LUA_MINSTACK
;
363 if (!lua_checkstack(L
, space
+ extra
)) {
365 luaL_error(L
, "stack overflow (%s)", msg
);
367 luaL_error(L
, "stack overflow");
372 LUALIB_API
void luaL_checktype (lua_State
*L
, int arg
, int t
) {
373 if (lua_type(L
, arg
) != t
)
374 tag_error(L
, arg
, t
);
378 LUALIB_API
void luaL_checkany (lua_State
*L
, int arg
) {
379 if (lua_type(L
, arg
) == LUA_TNONE
)
380 luaL_argerror(L
, arg
, "value expected");
384 LUALIB_API
const char *luaL_checklstring (lua_State
*L
, int arg
, size_t *len
) {
385 const char *s
= lua_tolstring(L
, arg
, len
);
386 if (!s
) tag_error(L
, arg
, LUA_TSTRING
);
391 LUALIB_API
const char *luaL_optlstring (lua_State
*L
, int arg
,
392 const char *def
, size_t *len
) {
393 if (lua_isnoneornil(L
, arg
)) {
395 *len
= (def
? strlen(def
) : 0);
398 else return luaL_checklstring(L
, arg
, len
);
402 LUALIB_API lua_Number
luaL_checknumber (lua_State
*L
, int arg
) {
404 lua_Number d
= lua_tonumberx(L
, arg
, &isnum
);
406 tag_error(L
, arg
, LUA_TNUMBER
);
411 LUALIB_API lua_Number
luaL_optnumber (lua_State
*L
, int arg
, lua_Number def
) {
412 return luaL_opt(L
, luaL_checknumber
, arg
, def
);
417 static void interror (lua_State
*L
, int arg
) {
418 if (lua_isnumber(L
, arg
))
419 luaL_argerror(L
, arg
, "number has no integer representation");
421 tag_error(L
, arg
, LUA_TNUMBER
);
425 LUALIB_API lua_Integer
luaL_checkinteger (lua_State
*L
, int arg
) {
427 lua_Integer d
= lua_tointegerx(L
, arg
, &isnum
);
435 LUALIB_API lua_Integer
luaL_optinteger (lua_State
*L
, int arg
,
437 return luaL_opt(L
, luaL_checkinteger
, arg
, def
);
441 /* }====================================================== */
445 ** {======================================================
446 ** Generic Buffer manipulation
447 ** =======================================================
451 ** check whether buffer is using a userdata on the stack as a temporary
454 #define buffonstack(B) ((B)->b != (B)->initb)
458 ** returns a pointer to a free area with at least 'sz' bytes
460 LUALIB_API
char *luaL_prepbuffsize (luaL_Buffer
*B
, size_t sz
) {
462 if (B
->size
- B
->n
< sz
) { /* not enough space? */
464 size_t newsize
= B
->size
* 2; /* double buffer size */
465 if (newsize
- B
->n
< sz
) /* not big enough? */
467 if (newsize
< B
->n
|| newsize
- B
->n
< sz
)
468 luaL_error(L
, "buffer too large");
469 /* create larger buffer */
470 newbuff
= (char *)lua_newuserdata(L
, newsize
* sizeof(char));
471 /* move content to new buffer */
472 memcpy(newbuff
, B
->b
, B
->n
* sizeof(char));
474 lua_remove(L
, -2); /* remove old buffer */
482 LUALIB_API
void luaL_addlstring (luaL_Buffer
*B
, const char *s
, size_t l
) {
483 char *b
= luaL_prepbuffsize(B
, l
);
484 memcpy(b
, s
, l
* sizeof(char));
489 LUALIB_API
void luaL_addstring (luaL_Buffer
*B
, const char *s
) {
490 luaL_addlstring(B
, s
, strlen(s
));
494 LUALIB_API
void luaL_pushresult (luaL_Buffer
*B
) {
496 lua_pushlstring(L
, B
->b
, B
->n
);
498 lua_remove(L
, -2); /* remove old buffer */
502 LUALIB_API
void luaL_pushresultsize (luaL_Buffer
*B
, size_t sz
) {
508 LUALIB_API
void luaL_addvalue (luaL_Buffer
*B
) {
511 const char *s
= lua_tolstring(L
, -1, &l
);
513 lua_insert(L
, -2); /* put value below buffer */
514 luaL_addlstring(B
, s
, l
);
515 lua_remove(L
, (buffonstack(B
)) ? -2 : -1); /* remove value */
519 LUALIB_API
void luaL_buffinit (lua_State
*L
, luaL_Buffer
*B
) {
523 B
->size
= LUAL_BUFFERSIZE
;
527 LUALIB_API
char *luaL_buffinitsize (lua_State
*L
, luaL_Buffer
*B
, size_t sz
) {
529 return luaL_prepbuffsize(B
, sz
);
532 /* }====================================================== */
536 ** {======================================================
538 ** =======================================================
541 /* index of free-list header */
545 LUALIB_API
int luaL_ref (lua_State
*L
, int t
) {
547 if (lua_isnil(L
, -1)) {
548 lua_pop(L
, 1); /* remove from stack */
549 return LUA_REFNIL
; /* 'nil' has a unique fixed reference */
551 t
= lua_absindex(L
, t
);
552 lua_rawgeti(L
, t
, freelist
); /* get first free element */
553 ref
= (int)lua_tointeger(L
, -1); /* ref = t[freelist] */
554 lua_pop(L
, 1); /* remove it from stack */
555 if (ref
!= 0) { /* any free element? */
556 lua_rawgeti(L
, t
, ref
); /* remove it from list */
557 lua_rawseti(L
, t
, freelist
); /* (t[freelist] = t[ref]) */
559 else /* no free elements */
560 ref
= (int)lua_rawlen(L
, t
) + 1; /* get a new reference */
561 lua_rawseti(L
, t
, ref
);
566 LUALIB_API
void luaL_unref (lua_State
*L
, int t
, int ref
) {
568 t
= lua_absindex(L
, t
);
569 lua_rawgeti(L
, t
, freelist
);
570 lua_rawseti(L
, t
, ref
); /* t[ref] = t[freelist] */
571 lua_pushinteger(L
, ref
);
572 lua_rawseti(L
, t
, freelist
); /* t[freelist] = ref */
576 /* }====================================================== */
580 ** {======================================================
582 ** =======================================================
586 typedef struct LoadF
{
587 int n
; /* number of pre-read characters */
588 FILE *f
; /* file being read */
589 char buff
[BUFSIZ
]; /* area for reading file */
593 static const char *getF (lua_State
*L
, void *ud
, size_t *size
) {
594 LoadF
*lf
= (LoadF
*)ud
;
595 (void)L
; /* not used */
596 if (lf
->n
> 0) { /* are there pre-read characters to be read? */
597 *size
= lf
->n
; /* return them (chars already in buffer) */
598 lf
->n
= 0; /* no more pre-read characters */
600 else { /* read a block from file */
601 /* 'fread' can return > 0 *and* set the EOF flag. If next call to
602 'getF' called 'fread', it might still wait for user input.
603 The next check avoids this problem. */
604 if (feof(lf
->f
)) return NULL
;
605 *size
= fread(lf
->buff
, 1, sizeof(lf
->buff
), lf
->f
); /* read block */
611 static int errfile (lua_State
*L
, const char *what
, int fnameindex
) {
612 const char *serr
= strerror(errno
);
613 const char *filename
= lua_tostring(L
, fnameindex
) + 1;
614 lua_pushfstring(L
, "cannot %s %s: %s", what
, filename
, serr
);
615 lua_remove(L
, fnameindex
);
620 static int skipBOM (LoadF
*lf
) {
621 const char *p
= "\xEF\xBB\xBF"; /* Utf8 BOM mark */
626 if (c
== EOF
|| c
!= *(const unsigned char *)p
++) return c
;
627 lf
->buff
[lf
->n
++] = c
; /* to be read by the parser */
628 } while (*p
!= '\0');
629 lf
->n
= 0; /* prefix matched; discard it */
630 return getc(lf
->f
); /* return next character */
635 ** reads the first character of file 'f' and skips an optional BOM mark
636 ** in its beginning plus its first line if it starts with '#'. Returns
637 ** true if it skipped the first line. In any case, '*cp' has the
638 ** first "valid" character of the file (after the optional BOM and
639 ** a first-line comment).
641 static int skipcomment (LoadF
*lf
, int *cp
) {
642 int c
= *cp
= skipBOM(lf
);
643 if (c
== '#') { /* first line is a comment (Unix exec. file)? */
644 do { /* skip first line */
646 } while (c
!= EOF
&& c
!= '\n') ;
647 *cp
= getc(lf
->f
); /* skip end-of-line, if present */
648 return 1; /* there was a comment */
650 else return 0; /* no comment */
654 LUALIB_API
int luaL_loadfilex (lua_State
*L
, const char *filename
,
657 int status
, readstatus
;
659 int fnameindex
= lua_gettop(L
) + 1; /* index of filename on the stack */
660 if (filename
== NULL
) {
661 lua_pushliteral(L
, "=stdin");
665 lua_pushfstring(L
, "@%s", filename
);
666 lf
.f
= fopen(filename
, "r");
667 if (lf
.f
== NULL
) return errfile(L
, "open", fnameindex
);
669 if (skipcomment(&lf
, &c
)) /* read initial portion */
670 lf
.buff
[lf
.n
++] = '\n'; /* add line to correct line numbers */
671 if (c
== LUA_SIGNATURE
[0] && filename
) { /* binary file? */
672 lf
.f
= freopen(filename
, "rb", lf
.f
); /* reopen in binary mode */
673 if (lf
.f
== NULL
) return errfile(L
, "reopen", fnameindex
);
674 skipcomment(&lf
, &c
); /* re-read initial portion */
677 lf
.buff
[lf
.n
++] = c
; /* 'c' is the first character of the stream */
678 status
= lua_load(L
, getF
, &lf
, lua_tostring(L
, -1), mode
);
679 readstatus
= ferror(lf
.f
);
680 if (filename
) fclose(lf
.f
); /* close file (even in case of errors) */
682 lua_settop(L
, fnameindex
); /* ignore results from 'lua_load' */
683 return errfile(L
, "read", fnameindex
);
685 lua_remove(L
, fnameindex
);
691 typedef struct LoadS
{
697 static const char *getS (lua_State
*L
, void *ud
, size_t *size
) {
698 LoadS
*ls
= (LoadS
*)ud
;
699 (void)L
; /* not used */
700 if (ls
->size
== 0) return NULL
;
707 LUALIB_API
int luaL_loadbufferx (lua_State
*L
, const char *buff
, size_t size
,
708 const char *name
, const char *mode
) {
712 return lua_load(L
, getS
, &ls
, name
, mode
);
716 LUALIB_API
int luaL_loadstring (lua_State
*L
, const char *s
) {
717 return luaL_loadbuffer(L
, s
, strlen(s
), s
);
720 /* }====================================================== */
724 LUALIB_API
int luaL_getmetafield (lua_State
*L
, int obj
, const char *event
) {
725 if (!lua_getmetatable(L
, obj
)) /* no metatable? */
729 lua_pushstring(L
, event
);
730 tt
= lua_rawget(L
, -2);
731 if (tt
== LUA_TNIL
) /* is metafield nil? */
732 lua_pop(L
, 2); /* remove metatable and metafield */
734 lua_remove(L
, -2); /* remove only metatable */
735 return tt
; /* return metafield type */
740 LUALIB_API
int luaL_callmeta (lua_State
*L
, int obj
, const char *event
) {
741 obj
= lua_absindex(L
, obj
);
742 if (luaL_getmetafield(L
, obj
, event
) == LUA_TNIL
) /* no metafield? */
744 lua_pushvalue(L
, obj
);
750 LUALIB_API lua_Integer
luaL_len (lua_State
*L
, int idx
) {
754 l
= lua_tointegerx(L
, -1, &isnum
);
756 luaL_error(L
, "object length is not an integer");
757 lua_pop(L
, 1); /* remove object */
762 LUALIB_API
const char *luaL_tolstring (lua_State
*L
, int idx
, size_t *len
) {
763 if (!luaL_callmeta(L
, idx
, "__tostring")) { /* no metafield? */
764 switch (lua_type(L
, idx
)) {
766 if (lua_isinteger(L
, idx
))
767 lua_pushfstring(L
, "%I", lua_tointeger(L
, idx
));
769 lua_pushfstring(L
, "%f", lua_tonumber(L
, idx
));
773 lua_pushvalue(L
, idx
);
776 lua_pushstring(L
, (lua_toboolean(L
, idx
) ? "true" : "false"));
779 lua_pushliteral(L
, "nil");
782 lua_pushfstring(L
, "%s: %p", luaL_typename(L
, idx
),
783 lua_topointer(L
, idx
));
787 return lua_tolstring(L
, -1, len
);
792 ** {======================================================
793 ** Compatibility with 5.1 module functions
794 ** =======================================================
796 #if defined(LUA_COMPAT_MODULE)
798 static const char *luaL_findtable (lua_State
*L
, int idx
,
799 const char *fname
, int szhint
) {
801 if (idx
) lua_pushvalue(L
, idx
);
803 e
= strchr(fname
, '.');
804 if (e
== NULL
) e
= fname
+ strlen(fname
);
805 lua_pushlstring(L
, fname
, e
- fname
);
806 if (lua_rawget(L
, -2) == LUA_TNIL
) { /* no such field? */
807 lua_pop(L
, 1); /* remove this nil */
808 lua_createtable(L
, 0, (*e
== '.' ? 1 : szhint
)); /* new table for field */
809 lua_pushlstring(L
, fname
, e
- fname
);
810 lua_pushvalue(L
, -2);
811 lua_settable(L
, -4); /* set new table into field */
813 else if (!lua_istable(L
, -1)) { /* field has a non-table value? */
814 lua_pop(L
, 2); /* remove table and value */
815 return fname
; /* return problematic part of the name */
817 lua_remove(L
, -2); /* remove previous table */
825 ** Count number of elements in a luaL_Reg list.
827 static int libsize (const luaL_Reg
*l
) {
829 for (; l
&& l
->name
; l
++) size
++;
835 ** Find or create a module table with a given name. The function
836 ** first looks at the _LOADED table and, if that fails, try a
837 ** global variable with that name. In any case, leaves on the stack
840 LUALIB_API
void luaL_pushmodule (lua_State
*L
, const char *modname
,
842 luaL_findtable(L
, LUA_REGISTRYINDEX
, "_LOADED", 1); /* get _LOADED table */
843 if (lua_getfield(L
, -1, modname
) != LUA_TTABLE
) { /* no _LOADED[modname]? */
844 lua_pop(L
, 1); /* remove previous result */
845 /* try global variable (and create one if it does not exist) */
846 lua_pushglobaltable(L
);
847 if (luaL_findtable(L
, 0, modname
, sizehint
) != NULL
)
848 luaL_error(L
, "name conflict for module '%s'", modname
);
849 lua_pushvalue(L
, -1);
850 lua_setfield(L
, -3, modname
); /* _LOADED[modname] = new table */
852 lua_remove(L
, -2); /* remove _LOADED table */
856 LUALIB_API
void luaL_openlib (lua_State
*L
, const char *libname
,
857 const luaL_Reg
*l
, int nup
) {
858 luaL_checkversion(L
);
860 luaL_pushmodule(L
, libname
, libsize(l
)); /* get/create library table */
861 lua_insert(L
, -(nup
+ 1)); /* move library table to below upvalues */
864 luaL_setfuncs(L
, l
, nup
);
866 lua_pop(L
, nup
); /* remove upvalues */
870 /* }====================================================== */
873 ** set functions from list 'l' into table at top - 'nup'; each
874 ** function gets the 'nup' elements at the top as upvalues.
875 ** Returns with only the table at the stack.
877 LUALIB_API
void luaL_setfuncs (lua_State
*L
, const luaL_Reg
*l
, int nup
) {
878 luaL_checkstack(L
, nup
, "too many upvalues");
879 for (; l
->name
!= NULL
; l
++) { /* fill the table with given functions */
881 for (i
= 0; i
< nup
; i
++) /* copy upvalues to the top */
882 lua_pushvalue(L
, -nup
);
883 lua_pushcclosure(L
, l
->func
, nup
); /* closure with those upvalues */
884 lua_setfield(L
, -(nup
+ 2), l
->name
);
886 lua_pop(L
, nup
); /* remove upvalues */
891 ** ensure that stack[idx][fname] has a table and push that table
894 LUALIB_API
int luaL_getsubtable (lua_State
*L
, int idx
, const char *fname
) {
895 if (lua_getfield(L
, idx
, fname
) == LUA_TTABLE
)
896 return 1; /* table already there */
898 lua_pop(L
, 1); /* remove previous result */
899 idx
= lua_absindex(L
, idx
);
901 lua_pushvalue(L
, -1); /* copy to be left at top */
902 lua_setfield(L
, idx
, fname
); /* assign new table to field */
903 return 0; /* false, because did not find table there */
909 ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
910 ** to open a module, registers the result in 'package.loaded' table and,
911 ** if 'glb' is true, also registers the result in the global table.
912 ** Leaves resulting module on the top.
914 LUALIB_API
void luaL_requiref (lua_State
*L
, const char *modname
,
915 lua_CFunction openf
, int glb
) {
916 luaL_getsubtable(L
, LUA_REGISTRYINDEX
, "_LOADED");
917 lua_getfield(L
, -1, modname
); /* _LOADED[modname] */
918 if (!lua_toboolean(L
, -1)) { /* package not already loaded? */
919 lua_pop(L
, 1); /* remove field */
920 lua_pushcfunction(L
, openf
);
921 lua_pushstring(L
, modname
); /* argument to open function */
922 lua_call(L
, 1, 1); /* call 'openf' to open module */
923 lua_pushvalue(L
, -1); /* make copy of module (call result) */
924 lua_setfield(L
, -3, modname
); /* _LOADED[modname] = module */
926 lua_remove(L
, -2); /* remove _LOADED table */
928 lua_pushvalue(L
, -1); /* copy of module */
929 lua_setglobal(L
, modname
); /* _G[modname] = module */
934 LUALIB_API
const char *luaL_gsub (lua_State
*L
, const char *s
, const char *p
,
937 size_t l
= strlen(p
);
939 luaL_buffinit(L
, &b
);
940 while ((wild
= strstr(s
, p
)) != NULL
) {
941 luaL_addlstring(&b
, s
, wild
- s
); /* push prefix */
942 luaL_addstring(&b
, r
); /* push replacement in place of pattern */
943 s
= wild
+ l
; /* continue after 'p' */
945 luaL_addstring(&b
, s
); /* push last suffix */
947 return lua_tostring(L
, -1);
952 static void *l_alloc (void *ud
, void *ptr
, size_t osize
, size_t nsize
) {
953 (void)ud
; (void)osize
; /* not used */
959 return realloc(ptr
, nsize
);
963 static int panic (lua_State
*L
) {
964 lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
965 lua_tostring(L
, -1));
966 return 0; /* return to Lua to abort */
970 LUALIB_API lua_State
*luaL_newstate (void) {
971 lua_State
*L
= lua_newstate(l_alloc
, NULL
);
972 if (L
) lua_atpanic(L
, &panic
);
978 LUALIB_API
void luaL_checkversion_ (lua_State
*L
, lua_Number ver
, size_t sz
) {
979 const lua_Number
*v
= lua_version(L
);
980 if (sz
!= LUAL_NUMSIZES
) /* check numeric types */
981 luaL_error(L
, "core and library have incompatible numeric types");
982 if (v
!= lua_version(NULL
))
983 luaL_error(L
, "multiple Lua VMs detected");
985 luaL_error(L
, "version mismatch: app. needs %f, Lua core provides %f",