2 ** $Id: lauxlib.c,v 1.248.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Auxiliary functions for building Lua libraries
4 ** See Copyright Notice in lua.h
8 /* This file uses only the official API of Lua.
9 ** Any function declared here could be written as an application function.
15 #include <sys/lua/lua.h>
17 #include <sys/lua/lauxlib.h>
21 ** {======================================================
23 ** =======================================================
27 #define LEVELS1 12 /* size of the first part of the stack */
28 #define LEVELS2 10 /* size of the second part of the stack */
33 ** search for 'objidx' in table at index -1.
34 ** return 1 + string at top if find a good name.
36 static int findfield (lua_State
*L
, int objidx
, int level
) {
37 if (level
== 0 || !lua_istable(L
, -1))
38 return 0; /* not found */
39 lua_pushnil(L
); /* start 'next' loop */
40 while (lua_next(L
, -2)) { /* for each pair in table */
41 if (lua_type(L
, -2) == LUA_TSTRING
) { /* ignore non-string keys */
42 if (lua_rawequal(L
, objidx
, -1)) { /* found object? */
43 lua_pop(L
, 1); /* remove value (but keep name) */
46 else if (findfield(L
, objidx
, level
- 1)) { /* try recursively */
47 lua_remove(L
, -2); /* remove table (but keep name) */
48 lua_pushliteral(L
, ".");
49 lua_insert(L
, -2); /* place '.' between the two names */
54 lua_pop(L
, 1); /* remove value */
56 return 0; /* not found */
60 static int pushglobalfuncname (lua_State
*L
, lua_Debug
*ar
) {
61 int top
= lua_gettop(L
);
62 lua_getinfo(L
, "f", ar
); /* push function */
63 lua_pushglobaltable(L
);
64 if (findfield(L
, top
+ 1, 2)) {
65 lua_copy(L
, -1, top
+ 1); /* move name to proper place */
66 lua_pop(L
, 2); /* remove pushed values */
70 lua_settop(L
, top
); /* remove function and global table */
76 static void pushfuncname (lua_State
*L
, lua_Debug
*ar
) {
77 if (*ar
->namewhat
!= '\0') /* is there a name? */
78 lua_pushfstring(L
, "function " LUA_QS
, ar
->name
);
79 else if (*ar
->what
== 'm') /* main? */
80 lua_pushliteral(L
, "main chunk");
81 else if (*ar
->what
== 'C') {
82 if (pushglobalfuncname(L
, ar
)) {
83 lua_pushfstring(L
, "function " LUA_QS
, lua_tostring(L
, -1));
84 lua_remove(L
, -2); /* remove name */
87 lua_pushliteral(L
, "?");
90 lua_pushfstring(L
, "function <%s:%d>", ar
->short_src
, ar
->linedefined
);
94 static int countlevels (lua_State
*L
) {
97 /* find an upper bound */
98 while (lua_getstack(L
, le
, &ar
)) { li
= le
; le
*= 2; }
99 /* do a binary search */
102 if (lua_getstack(L
, m
, &ar
)) li
= m
+ 1;
109 LUALIB_API
void luaL_traceback (lua_State
*L
, lua_State
*L1
,
110 const char *msg
, int level
) {
112 int top
= lua_gettop(L
);
113 int numlevels
= countlevels(L1
);
114 int mark
= (numlevels
> LEVELS1
+ LEVELS2
) ? LEVELS1
: 0;
115 if (msg
) lua_pushfstring(L
, "%s\n", msg
);
116 lua_pushliteral(L
, "stack traceback:");
117 while (lua_getstack(L1
, level
++, &ar
)) {
118 if (level
== mark
) { /* too many levels? */
119 lua_pushliteral(L
, "\n\t..."); /* add a '...' */
120 level
= numlevels
- LEVELS2
; /* and skip to last ones */
123 lua_getinfo(L1
, "Slnt", &ar
);
124 lua_pushfstring(L
, "\n\t%s:", ar
.short_src
);
125 if (ar
.currentline
> 0)
126 lua_pushfstring(L
, "%d:", ar
.currentline
);
127 lua_pushliteral(L
, " in ");
128 pushfuncname(L
, &ar
);
130 lua_pushliteral(L
, "\n\t(...tail calls...)");
131 lua_concat(L
, lua_gettop(L
) - top
);
134 lua_concat(L
, lua_gettop(L
) - top
);
137 /* }====================================================== */
141 ** {======================================================
142 ** Error-report functions
143 ** =======================================================
146 LUALIB_API
int luaL_argerror (lua_State
*L
, int narg
, const char *extramsg
) {
148 if (!lua_getstack(L
, 0, &ar
)) /* no stack frame? */
149 return luaL_error(L
, "bad argument #%d (%s)", narg
, extramsg
);
150 lua_getinfo(L
, "n", &ar
);
151 if (strcmp(ar
.namewhat
, "method") == 0) {
152 narg
--; /* do not count `self' */
153 if (narg
== 0) /* error is in the self argument itself? */
154 return luaL_error(L
, "calling " LUA_QS
" on bad self (%s)",
158 ar
.name
= (pushglobalfuncname(L
, &ar
)) ? lua_tostring(L
, -1) : "?";
159 return luaL_error(L
, "bad argument #%d to " LUA_QS
" (%s)",
160 narg
, ar
.name
, extramsg
);
164 static int typeerror (lua_State
*L
, int narg
, const char *tname
) {
165 const char *msg
= lua_pushfstring(L
, "%s expected, got %s",
166 tname
, luaL_typename(L
, narg
));
167 return luaL_argerror(L
, narg
, msg
);
171 static void tag_error (lua_State
*L
, int narg
, int tag
) {
172 typeerror(L
, narg
, lua_typename(L
, tag
));
176 LUALIB_API
void luaL_where (lua_State
*L
, int level
) {
178 if (lua_getstack(L
, level
, &ar
)) { /* check function at level */
179 lua_getinfo(L
, "Sl", &ar
); /* get info about it */
180 if (ar
.currentline
> 0) { /* is there info? */
181 lua_pushfstring(L
, "%s:%d: ", ar
.short_src
, ar
.currentline
);
185 lua_pushliteral(L
, ""); /* else, no information available... */
189 LUALIB_API
int luaL_error (lua_State
*L
, const char *fmt
, ...) {
193 lua_pushvfstring(L
, fmt
, argp
);
200 #if !defined(inspectstat) /* { */
202 #if defined(LUA_USE_POSIX)
204 #include <sys/wait.h>
207 ** use appropriate macros to interpret 'pclose' return status
209 #define inspectstat(stat,what) \
210 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
211 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
215 #define inspectstat(stat,what) /* no op */
222 /* }====================================================== */
226 ** {======================================================
227 ** Userdata's metatable manipulation
228 ** =======================================================
231 LUALIB_API
int luaL_newmetatable (lua_State
*L
, const char *tname
) {
232 luaL_getmetatable(L
, tname
); /* try to get metatable */
233 if (!lua_isnil(L
, -1)) /* name already in use? */
234 return 0; /* leave previous value on top, but return 0 */
236 lua_newtable(L
); /* create metatable */
237 lua_pushvalue(L
, -1);
238 lua_setfield(L
, LUA_REGISTRYINDEX
, tname
); /* registry.name = metatable */
243 LUALIB_API
void luaL_setmetatable (lua_State
*L
, const char *tname
) {
244 luaL_getmetatable(L
, tname
);
245 lua_setmetatable(L
, -2);
249 LUALIB_API
void *luaL_testudata (lua_State
*L
, int ud
, const char *tname
) {
250 void *p
= lua_touserdata(L
, ud
);
251 if (p
!= NULL
) { /* value is a userdata? */
252 if (lua_getmetatable(L
, ud
)) { /* does it have a metatable? */
253 luaL_getmetatable(L
, tname
); /* get correct metatable */
254 if (!lua_rawequal(L
, -1, -2)) /* not the same? */
255 p
= NULL
; /* value is a userdata with wrong metatable */
256 lua_pop(L
, 2); /* remove both metatables */
260 return NULL
; /* value is not a userdata with a metatable */
264 LUALIB_API
void *luaL_checkudata (lua_State
*L
, int ud
, const char *tname
) {
265 void *p
= luaL_testudata(L
, ud
, tname
);
266 if (p
== NULL
) typeerror(L
, ud
, tname
);
270 /* }====================================================== */
274 ** {======================================================
275 ** Argument check functions
276 ** =======================================================
279 LUALIB_API
int luaL_checkoption (lua_State
*L
, int narg
, const char *def
,
280 const char *const lst
[]) {
281 const char *name
= (def
) ? luaL_optstring(L
, narg
, def
) :
282 luaL_checkstring(L
, narg
);
284 for (i
=0; lst
[i
]; i
++)
285 if (strcmp(lst
[i
], name
) == 0)
287 return luaL_argerror(L
, narg
,
288 lua_pushfstring(L
, "invalid option " LUA_QS
, name
));
292 LUALIB_API
void luaL_checkstack (lua_State
*L
, int space
, const char *msg
) {
293 /* keep some extra space to run error routines, if needed */
294 const int extra
= LUA_MINSTACK
;
295 if (!lua_checkstack(L
, space
+ extra
)) {
297 luaL_error(L
, "stack overflow (%s)", msg
);
299 luaL_error(L
, "stack overflow");
304 LUALIB_API
void luaL_checktype (lua_State
*L
, int narg
, int t
) {
305 if (lua_type(L
, narg
) != t
)
306 tag_error(L
, narg
, t
);
310 LUALIB_API
void luaL_checkany (lua_State
*L
, int narg
) {
311 if (lua_type(L
, narg
) == LUA_TNONE
)
312 luaL_argerror(L
, narg
, "value expected");
316 LUALIB_API
const char *luaL_checklstring (lua_State
*L
, int narg
, size_t *len
) {
317 const char *s
= lua_tolstring(L
, narg
, len
);
318 if (!s
) tag_error(L
, narg
, LUA_TSTRING
);
323 LUALIB_API
const char *luaL_optlstring (lua_State
*L
, int narg
,
324 const char *def
, size_t *len
) {
325 if (lua_isnoneornil(L
, narg
)) {
327 *len
= (def
? strlen(def
) : 0);
330 else return luaL_checklstring(L
, narg
, len
);
334 LUALIB_API lua_Number
luaL_checknumber (lua_State
*L
, int narg
) {
336 lua_Number d
= lua_tonumberx(L
, narg
, &isnum
);
338 tag_error(L
, narg
, LUA_TNUMBER
);
343 LUALIB_API lua_Number
luaL_optnumber (lua_State
*L
, int narg
, lua_Number def
) {
344 return luaL_opt(L
, luaL_checknumber
, narg
, def
);
348 LUALIB_API lua_Integer
luaL_checkinteger (lua_State
*L
, int narg
) {
350 lua_Integer d
= lua_tointegerx(L
, narg
, &isnum
);
352 tag_error(L
, narg
, LUA_TNUMBER
);
357 LUALIB_API lua_Unsigned
luaL_checkunsigned (lua_State
*L
, int narg
) {
359 lua_Unsigned d
= lua_tounsignedx(L
, narg
, &isnum
);
361 tag_error(L
, narg
, LUA_TNUMBER
);
366 LUALIB_API lua_Integer
luaL_optinteger (lua_State
*L
, int narg
,
368 return luaL_opt(L
, luaL_checkinteger
, narg
, def
);
372 LUALIB_API lua_Unsigned
luaL_optunsigned (lua_State
*L
, int narg
,
374 return luaL_opt(L
, luaL_checkunsigned
, narg
, def
);
377 /* }====================================================== */
381 ** {======================================================
382 ** Generic Buffer manipulation
383 ** =======================================================
387 ** check whether buffer is using a userdata on the stack as a temporary
390 #define buffonstack(B) ((B)->b != (B)->initb)
394 ** returns a pointer to a free area with at least 'sz' bytes
396 LUALIB_API
char *luaL_prepbuffsize (luaL_Buffer
*B
, size_t sz
) {
398 if (B
->size
- B
->n
< sz
) { /* not enough space? */
400 size_t newsize
= B
->size
* 2; /* double buffer size */
401 if (newsize
- B
->n
< sz
) /* not big enough? */
403 if (newsize
< B
->n
|| newsize
- B
->n
< sz
)
404 luaL_error(L
, "buffer too large");
405 /* create larger buffer */
406 newbuff
= (char *)lua_newuserdata(L
, newsize
* sizeof(char));
407 /* move content to new buffer */
408 memcpy(newbuff
, B
->b
, B
->n
* sizeof(char));
410 lua_remove(L
, -2); /* remove old buffer */
418 LUALIB_API
void luaL_addlstring (luaL_Buffer
*B
, const char *s
, size_t l
) {
419 char *b
= luaL_prepbuffsize(B
, l
);
420 memcpy(b
, s
, l
* sizeof(char));
425 LUALIB_API
void luaL_addstring (luaL_Buffer
*B
, const char *s
) {
426 luaL_addlstring(B
, s
, strlen(s
));
430 LUALIB_API
void luaL_pushresult (luaL_Buffer
*B
) {
432 lua_pushlstring(L
, B
->b
, B
->n
);
434 lua_remove(L
, -2); /* remove old buffer */
438 LUALIB_API
void luaL_pushresultsize (luaL_Buffer
*B
, size_t sz
) {
444 LUALIB_API
void luaL_addvalue (luaL_Buffer
*B
) {
447 const char *s
= lua_tolstring(L
, -1, &l
);
449 lua_insert(L
, -2); /* put value below buffer */
450 luaL_addlstring(B
, s
, l
);
451 lua_remove(L
, (buffonstack(B
)) ? -2 : -1); /* remove value */
455 LUALIB_API
void luaL_buffinit (lua_State
*L
, luaL_Buffer
*B
) {
459 B
->size
= LUAL_BUFFERSIZE
;
463 LUALIB_API
char *luaL_buffinitsize (lua_State
*L
, luaL_Buffer
*B
, size_t sz
) {
465 return luaL_prepbuffsize(B
, sz
);
468 /* }====================================================== */
472 ** {======================================================
474 ** =======================================================
477 /* index of free-list header */
481 LUALIB_API
int luaL_ref (lua_State
*L
, int t
) {
483 if (lua_isnil(L
, -1)) {
484 lua_pop(L
, 1); /* remove from stack */
485 return LUA_REFNIL
; /* `nil' has a unique fixed reference */
487 t
= lua_absindex(L
, t
);
488 lua_rawgeti(L
, t
, freelist
); /* get first free element */
489 ref
= (int)lua_tointeger(L
, -1); /* ref = t[freelist] */
490 lua_pop(L
, 1); /* remove it from stack */
491 if (ref
!= 0) { /* any free element? */
492 lua_rawgeti(L
, t
, ref
); /* remove it from list */
493 lua_rawseti(L
, t
, freelist
); /* (t[freelist] = t[ref]) */
495 else /* no free elements */
496 ref
= (int)lua_rawlen(L
, t
) + 1; /* get a new reference */
497 lua_rawseti(L
, t
, ref
);
502 LUALIB_API
void luaL_unref (lua_State
*L
, int t
, int ref
) {
504 t
= lua_absindex(L
, t
);
505 lua_rawgeti(L
, t
, freelist
);
506 lua_rawseti(L
, t
, ref
); /* t[ref] = t[freelist] */
507 lua_pushinteger(L
, ref
);
508 lua_rawseti(L
, t
, freelist
); /* t[freelist] = ref */
512 /* }====================================================== */
516 ** {======================================================
518 ** =======================================================
521 typedef struct LoadS
{
527 static const char *getS (lua_State
*L
, void *ud
, size_t *size
) {
528 LoadS
*ls
= (LoadS
*)ud
;
529 (void)L
; /* not used */
530 if (ls
->size
== 0) return NULL
;
537 LUALIB_API
int luaL_loadbufferx (lua_State
*L
, const char *buff
, size_t size
,
538 const char *name
, const char *mode
) {
542 return lua_load(L
, getS
, &ls
, name
, mode
);
546 LUALIB_API
int luaL_loadstring (lua_State
*L
, const char *s
) {
547 return luaL_loadbuffer(L
, s
, strlen(s
), s
);
550 /* }====================================================== */
554 LUALIB_API
int luaL_getmetafield (lua_State
*L
, int obj
, const char *event
) {
555 if (!lua_getmetatable(L
, obj
)) /* no metatable? */
557 lua_pushstring(L
, event
);
559 if (lua_isnil(L
, -1)) {
560 lua_pop(L
, 2); /* remove metatable and metafield */
564 lua_remove(L
, -2); /* remove only metatable */
570 LUALIB_API
int luaL_callmeta (lua_State
*L
, int obj
, const char *event
) {
571 obj
= lua_absindex(L
, obj
);
572 if (!luaL_getmetafield(L
, obj
, event
)) /* no metafield? */
574 lua_pushvalue(L
, obj
);
580 LUALIB_API
int luaL_len (lua_State
*L
, int idx
) {
584 l
= (int)lua_tointegerx(L
, -1, &isnum
);
586 luaL_error(L
, "object length is not a number");
587 lua_pop(L
, 1); /* remove object */
592 LUALIB_API
const char *luaL_tolstring (lua_State
*L
, int idx
, size_t *len
) {
593 if (!luaL_callmeta(L
, idx
, "__tostring")) { /* no metafield? */
594 switch (lua_type(L
, idx
)) {
597 lua_pushvalue(L
, idx
);
600 lua_pushstring(L
, (lua_toboolean(L
, idx
) ? "true" : "false"));
603 lua_pushliteral(L
, "nil");
606 lua_pushfstring(L
, "%s: %p", luaL_typename(L
, idx
),
607 lua_topointer(L
, idx
));
611 return lua_tolstring(L
, -1, len
);
616 ** {======================================================
617 ** Compatibility with 5.1 module functions
618 ** =======================================================
620 #if defined(LUA_COMPAT_MODULE)
622 static const char *luaL_findtable (lua_State
*L
, int idx
,
623 const char *fname
, int szhint
) {
625 if (idx
) lua_pushvalue(L
, idx
);
627 e
= strchr(fname
, '.');
628 if (e
== NULL
) e
= fname
+ strlen(fname
);
629 lua_pushlstring(L
, fname
, e
- fname
);
631 if (lua_isnil(L
, -1)) { /* no such field? */
632 lua_pop(L
, 1); /* remove this nil */
633 lua_createtable(L
, 0, (*e
== '.' ? 1 : szhint
)); /* new table for field */
634 lua_pushlstring(L
, fname
, e
- fname
);
635 lua_pushvalue(L
, -2);
636 lua_settable(L
, -4); /* set new table into field */
638 else if (!lua_istable(L
, -1)) { /* field has a non-table value? */
639 lua_pop(L
, 2); /* remove table and value */
640 return fname
; /* return problematic part of the name */
642 lua_remove(L
, -2); /* remove previous table */
650 ** Count number of elements in a luaL_Reg list.
652 static int libsize (const luaL_Reg
*l
) {
654 for (; l
&& l
->name
; l
++) size
++;
660 ** Find or create a module table with a given name. The function
661 ** first looks at the _LOADED table and, if that fails, try a
662 ** global variable with that name. In any case, leaves on the stack
665 LUALIB_API
void luaL_pushmodule (lua_State
*L
, const char *modname
,
667 luaL_findtable(L
, LUA_REGISTRYINDEX
, "_LOADED", 1); /* get _LOADED table */
668 lua_getfield(L
, -1, modname
); /* get _LOADED[modname] */
669 if (!lua_istable(L
, -1)) { /* not found? */
670 lua_pop(L
, 1); /* remove previous result */
671 /* try global variable (and create one if it does not exist) */
672 lua_pushglobaltable(L
);
673 if (luaL_findtable(L
, 0, modname
, sizehint
) != NULL
)
674 luaL_error(L
, "name conflict for module " LUA_QS
, modname
);
675 lua_pushvalue(L
, -1);
676 lua_setfield(L
, -3, modname
); /* _LOADED[modname] = new table */
678 lua_remove(L
, -2); /* remove _LOADED table */
682 LUALIB_API
void luaL_openlib (lua_State
*L
, const char *libname
,
683 const luaL_Reg
*l
, int nup
) {
684 luaL_checkversion(L
);
686 luaL_pushmodule(L
, libname
, libsize(l
)); /* get/create library table */
687 lua_insert(L
, -(nup
+ 1)); /* move library table to below upvalues */
690 luaL_setfuncs(L
, l
, nup
);
692 lua_pop(L
, nup
); /* remove upvalues */
696 /* }====================================================== */
699 ** set functions from list 'l' into table at top - 'nup'; each
700 ** function gets the 'nup' elements at the top as upvalues.
701 ** Returns with only the table at the stack.
703 LUALIB_API
void luaL_setfuncs (lua_State
*L
, const luaL_Reg
*l
, int nup
) {
704 luaL_checkversion(L
);
705 luaL_checkstack(L
, nup
, "too many upvalues");
706 for (; l
->name
!= NULL
; l
++) { /* fill the table with given functions */
708 for (i
= 0; i
< nup
; i
++) /* copy upvalues to the top */
709 lua_pushvalue(L
, -nup
);
710 lua_pushcclosure(L
, l
->func
, nup
); /* closure with those upvalues */
711 lua_setfield(L
, -(nup
+ 2), l
->name
);
713 lua_pop(L
, nup
); /* remove upvalues */
718 ** ensure that stack[idx][fname] has a table and push that table
721 LUALIB_API
int luaL_getsubtable (lua_State
*L
, int idx
, const char *fname
) {
722 lua_getfield(L
, idx
, fname
);
723 if (lua_istable(L
, -1)) return 1; /* table already there */
725 lua_pop(L
, 1); /* remove previous result */
726 idx
= lua_absindex(L
, idx
);
728 lua_pushvalue(L
, -1); /* copy to be left at top */
729 lua_setfield(L
, idx
, fname
); /* assign new table to field */
730 return 0; /* false, because did not find table there */
736 ** stripped-down 'require'. Calls 'openf' to open a module,
737 ** registers the result in 'package.loaded' table and, if 'glb'
738 ** is true, also registers the result in the global table.
739 ** Leaves resulting module on the top.
741 LUALIB_API
void luaL_requiref (lua_State
*L
, const char *modname
,
742 lua_CFunction openf
, int glb
) {
743 lua_pushcfunction(L
, openf
);
744 lua_pushstring(L
, modname
); /* argument to open function */
745 lua_call(L
, 1, 1); /* open module */
746 luaL_getsubtable(L
, LUA_REGISTRYINDEX
, "_LOADED");
747 lua_pushvalue(L
, -2); /* make copy of module (call result) */
748 lua_setfield(L
, -2, modname
); /* _LOADED[modname] = module */
749 lua_pop(L
, 1); /* remove _LOADED table */
751 lua_pushvalue(L
, -1); /* copy of 'mod' */
752 lua_setglobal(L
, modname
); /* _G[modname] = module */
757 LUALIB_API
const char *luaL_gsub (lua_State
*L
, const char *s
, const char *p
,
760 size_t l
= strlen(p
);
762 luaL_buffinit(L
, &b
);
763 while ((wild
= strstr(s
, p
)) != NULL
) {
764 luaL_addlstring(&b
, s
, wild
- s
); /* push prefix */
765 luaL_addstring(&b
, r
); /* push replacement in place of pattern */
766 s
= wild
+ l
; /* continue after `p' */
768 luaL_addstring(&b
, s
); /* push last suffix */
770 return lua_tostring(L
, -1);
774 LUALIB_API
void luaL_checkversion_ (lua_State
*L
, lua_Number ver
) {
775 const lua_Number
*v
= lua_version(L
);
776 if (v
!= lua_version(NULL
))
777 luaL_error(L
, "multiple Lua VMs detected");
779 luaL_error(L
, "version mismatch: app. needs %f, Lua core provides %f",
781 /* check conversions number -> integer types */
782 lua_pushnumber(L
, -(lua_Number
)0x1234);
783 if (lua_tointeger(L
, -1) != -0x1234 ||
784 lua_tounsigned(L
, -1) != (lua_Unsigned
)-0x1234)
785 luaL_error(L
, "bad conversion number->int;"
786 " must recompile Lua with proper settings");
792 EXPORT_SYMBOL(luaL_argerror
);
793 EXPORT_SYMBOL(luaL_error
);
794 EXPORT_SYMBOL(luaL_loadbufferx
);
795 EXPORT_SYMBOL(luaL_newmetatable
);
796 EXPORT_SYMBOL(luaL_traceback
);