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 #include <sys/zfs_context.h>
10 /* This file uses only the official API of Lua.
11 ** Any function declared here could be written as an application function.
23 ** {======================================================
25 ** =======================================================
29 #define LEVELS1 12 /* size of the first part of the stack */
30 #define LEVELS2 10 /* size of the second part of the stack */
35 ** search for 'objidx' in table at index -1.
36 ** return 1 + string at top if find a good name.
38 static int findfield (lua_State *L, int objidx, int level) {
39 if (level == 0 || !lua_istable(L, -1))
40 return 0; /* not found */
41 lua_pushnil(L); /* start 'next' loop */
42 while (lua_next(L, -2)) { /* for each pair in table */
43 if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
44 if (lua_rawequal(L, objidx, -1)) { /* found object? */
45 lua_pop(L, 1); /* remove value (but keep name) */
48 else if (findfield(L, objidx, level - 1)) { /* try recursively */
49 lua_remove(L, -2); /* remove table (but keep name) */
50 lua_pushliteral(L, ".");
51 lua_insert(L, -2); /* place '.' between the two names */
56 lua_pop(L, 1); /* remove value */
58 return 0; /* not found */
62 static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
63 int top = lua_gettop(L);
64 lua_getinfo(L, "f", ar); /* push function */
65 lua_pushglobaltable(L);
66 if (findfield(L, top + 1, 2)) {
67 lua_copy(L, -1, top + 1); /* move name to proper place */
68 lua_pop(L, 2); /* remove pushed values */
72 lua_settop(L, top); /* remove function and global table */
78 static void pushfuncname (lua_State *L, lua_Debug *ar) {
79 if (*ar->namewhat != '\0') /* is there a name? */
80 lua_pushfstring(L, "function " LUA_QS, ar->name);
81 else if (*ar->what == 'm') /* main? */
82 lua_pushliteral(L, "main chunk");
83 else if (*ar->what == 'C') {
84 if (pushglobalfuncname(L, ar)) {
85 lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
86 lua_remove(L, -2); /* remove name */
89 lua_pushliteral(L, "?");
92 lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
96 static int countlevels (lua_State *L) {
99 /* find an upper bound */
100 while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
101 /* do a binary search */
104 if (lua_getstack(L, m, &ar)) li = m + 1;
111 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
112 const char *msg, int level) {
114 int top = lua_gettop(L);
115 int numlevels = countlevels(L1);
116 int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
117 if (msg) lua_pushfstring(L, "%s\n", msg);
118 lua_pushliteral(L, "stack traceback:");
119 while (lua_getstack(L1, level++, &ar)) {
120 if (level == mark) { /* too many levels? */
121 lua_pushliteral(L, "\n\t..."); /* add a '...' */
122 level = numlevels - LEVELS2; /* and skip to last ones */
125 lua_getinfo(L1, "Slnt", &ar);
126 lua_pushfstring(L, "\n\t%s:", ar.short_src);
127 if (ar.currentline > 0)
128 lua_pushfstring(L, "%d:", ar.currentline);
129 lua_pushliteral(L, " in ");
130 pushfuncname(L, &ar);
132 lua_pushliteral(L, "\n\t(...tail calls...)");
133 lua_concat(L, lua_gettop(L) - top);
136 lua_concat(L, lua_gettop(L) - top);
139 /* }====================================================== */
143 ** {======================================================
144 ** Error-report functions
145 ** =======================================================
148 LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
150 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
151 return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
152 lua_getinfo(L, "n", &ar);
153 if (strcmp(ar.namewhat, "method") == 0) {
154 narg--; /* do not count `self' */
155 if (narg == 0) /* error is in the self argument itself? */
156 return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
160 ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
161 return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
162 narg, ar.name, extramsg);
166 static int typeerror (lua_State *L, int narg, const char *tname) {
167 const char *msg = lua_pushfstring(L, "%s expected, got %s",
168 tname, luaL_typename(L, narg));
169 return luaL_argerror(L, narg, msg);
173 static void tag_error (lua_State *L, int narg, int tag) {
174 typeerror(L, narg, lua_typename(L, tag));
178 LUALIB_API void luaL_where (lua_State *L, int level) {
180 if (lua_getstack(L, level, &ar)) { /* check function at level */
181 lua_getinfo(L, "Sl", &ar); /* get info about it */
182 if (ar.currentline > 0) { /* is there info? */
183 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
187 lua_pushliteral(L, ""); /* else, no information available... */
191 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
195 lua_pushvfstring(L, fmt, argp);
202 #if !defined(inspectstat) /* { */
204 #if defined(LUA_USE_POSIX)
206 #include <sys/wait.h>
209 ** use appropriate macros to interpret 'pclose' return status
211 #define inspectstat(stat,what) \
212 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
213 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
217 #define inspectstat(stat,what) /* no op */
224 /* }====================================================== */
228 ** {======================================================
229 ** Userdata's metatable manipulation
230 ** =======================================================
233 LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
234 luaL_getmetatable(L, tname); /* try to get metatable */
235 if (!lua_isnil(L, -1)) /* name already in use? */
236 return 0; /* leave previous value on top, but return 0 */
238 lua_newtable(L); /* create metatable */
239 lua_pushvalue(L, -1);
240 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
245 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
246 luaL_getmetatable(L, tname);
247 lua_setmetatable(L, -2);
251 LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
252 void *p = lua_touserdata(L, ud);
253 if (p != NULL) { /* value is a userdata? */
254 if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
255 luaL_getmetatable(L, tname); /* get correct metatable */
256 if (!lua_rawequal(L, -1, -2)) /* not the same? */
257 p = NULL; /* value is a userdata with wrong metatable */
258 lua_pop(L, 2); /* remove both metatables */
262 return NULL; /* value is not a userdata with a metatable */
266 LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
267 void *p = luaL_testudata(L, ud, tname);
268 if (p == NULL) typeerror(L, ud, tname);
272 /* }====================================================== */
276 ** {======================================================
277 ** Argument check functions
278 ** =======================================================
281 LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
282 const char *const lst[]) {
283 const char *name = (def) ? luaL_optstring(L, narg, def) :
284 luaL_checkstring(L, narg);
286 for (i=0; lst[i]; i++)
287 if (strcmp(lst[i], name) == 0)
289 return luaL_argerror(L, narg,
290 lua_pushfstring(L, "invalid option " LUA_QS, name));
294 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
295 /* keep some extra space to run error routines, if needed */
296 const int extra = LUA_MINSTACK;
297 if (!lua_checkstack(L, space + extra)) {
299 luaL_error(L, "stack overflow (%s)", msg);
301 luaL_error(L, "stack overflow");
306 LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
307 if (lua_type(L, narg) != t)
308 tag_error(L, narg, t);
312 LUALIB_API void luaL_checkany (lua_State *L, int narg) {
313 if (lua_type(L, narg) == LUA_TNONE)
314 luaL_argerror(L, narg, "value expected");
318 LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
319 const char *s = lua_tolstring(L, narg, len);
320 if (!s) tag_error(L, narg, LUA_TSTRING);
325 LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
326 const char *def, size_t *len) {
327 if (lua_isnoneornil(L, narg)) {
329 *len = (def ? strlen(def) : 0);
332 else return luaL_checklstring(L, narg, len);
336 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
338 lua_Number d = lua_tonumberx(L, narg, &isnum);
340 tag_error(L, narg, LUA_TNUMBER);
345 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
346 return luaL_opt(L, luaL_checknumber, narg, def);
350 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
352 lua_Integer d = lua_tointegerx(L, narg, &isnum);
354 tag_error(L, narg, LUA_TNUMBER);
359 LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
361 lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
363 tag_error(L, narg, LUA_TNUMBER);
368 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
370 return luaL_opt(L, luaL_checkinteger, narg, def);
374 LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,
376 return luaL_opt(L, luaL_checkunsigned, narg, def);
379 /* }====================================================== */
383 ** {======================================================
384 ** Generic Buffer manipulation
385 ** =======================================================
389 ** check whether buffer is using a userdata on the stack as a temporary
392 #define buffonstack(B) ((B)->b != (B)->initb)
396 ** returns a pointer to a free area with at least 'sz' bytes
398 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
400 if (B->size - B->n < sz) { /* not enough space? */
402 size_t newsize = B->size * 2; /* double buffer size */
403 if (newsize - B->n < sz) /* not big enough? */
405 if (newsize < B->n || newsize - B->n < sz)
406 luaL_error(L, "buffer too large");
407 /* create larger buffer */
408 newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
409 /* move content to new buffer */
410 memcpy(newbuff, B->b, B->n * sizeof(char));
412 lua_remove(L, -2); /* remove old buffer */
420 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
421 char *b = luaL_prepbuffsize(B, l);
422 memcpy(b, s, l * sizeof(char));
427 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
428 luaL_addlstring(B, s, strlen(s));
432 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
434 lua_pushlstring(L, B->b, B->n);
436 lua_remove(L, -2); /* remove old buffer */
440 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
446 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
449 const char *s = lua_tolstring(L, -1, &l);
451 lua_insert(L, -2); /* put value below buffer */
452 luaL_addlstring(B, s, l);
453 lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
457 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
461 B->size = LUAL_BUFFERSIZE;
465 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
467 return luaL_prepbuffsize(B, sz);
470 /* }====================================================== */
474 ** {======================================================
476 ** =======================================================
479 /* index of free-list header */
483 LUALIB_API int luaL_ref (lua_State *L, int t) {
485 if (lua_isnil(L, -1)) {
486 lua_pop(L, 1); /* remove from stack */
487 return LUA_REFNIL; /* `nil' has a unique fixed reference */
489 t = lua_absindex(L, t);
490 lua_rawgeti(L, t, freelist); /* get first free element */
491 ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
492 lua_pop(L, 1); /* remove it from stack */
493 if (ref != 0) { /* any free element? */
494 lua_rawgeti(L, t, ref); /* remove it from list */
495 lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
497 else /* no free elements */
498 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
499 lua_rawseti(L, t, ref);
504 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
506 t = lua_absindex(L, t);
507 lua_rawgeti(L, t, freelist);
508 lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
509 lua_pushinteger(L, ref);
510 lua_rawseti(L, t, freelist); /* t[freelist] = ref */
514 /* }====================================================== */
518 ** {======================================================
520 ** =======================================================
523 typedef struct LoadS {
529 static const char *getS (lua_State *L, void *ud, size_t *size) {
530 LoadS *ls = (LoadS *)ud;
531 (void)L; /* not used */
532 if (ls->size == 0) return NULL;
539 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
540 const char *name, const char *mode) {
544 return lua_load(L, getS, &ls, name, mode);
548 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
549 return luaL_loadbuffer(L, s, strlen(s), s);
552 /* }====================================================== */
556 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
557 if (!lua_getmetatable(L, obj)) /* no metatable? */
559 lua_pushstring(L, event);
561 if (lua_isnil(L, -1)) {
562 lua_pop(L, 2); /* remove metatable and metafield */
566 lua_remove(L, -2); /* remove only metatable */
572 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
573 obj = lua_absindex(L, obj);
574 if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
576 lua_pushvalue(L, obj);
582 LUALIB_API int luaL_len (lua_State *L, int idx) {
586 l = (int)lua_tointegerx(L, -1, &isnum);
588 luaL_error(L, "object length is not a number");
589 lua_pop(L, 1); /* remove object */
594 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
595 if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
596 switch (lua_type(L, idx)) {
599 lua_pushvalue(L, idx);
602 lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
605 lua_pushliteral(L, "nil");
608 lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
609 lua_topointer(L, idx));
613 return lua_tolstring(L, -1, len);
618 ** {======================================================
619 ** Compatibility with 5.1 module functions
620 ** =======================================================
622 #if defined(LUA_COMPAT_MODULE)
624 static const char *luaL_findtable (lua_State *L, int idx,
625 const char *fname, int szhint) {
627 if (idx) lua_pushvalue(L, idx);
629 e = strchr(fname, '.');
630 if (e == NULL) e = fname + strlen(fname);
631 lua_pushlstring(L, fname, e - fname);
633 if (lua_isnil(L, -1)) { /* no such field? */
634 lua_pop(L, 1); /* remove this nil */
635 lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
636 lua_pushlstring(L, fname, e - fname);
637 lua_pushvalue(L, -2);
638 lua_settable(L, -4); /* set new table into field */
640 else if (!lua_istable(L, -1)) { /* field has a non-table value? */
641 lua_pop(L, 2); /* remove table and value */
642 return fname; /* return problematic part of the name */
644 lua_remove(L, -2); /* remove previous table */
652 ** Count number of elements in a luaL_Reg list.
654 static int libsize (const luaL_Reg *l) {
656 for (; l && l->name; l++) size++;
662 ** Find or create a module table with a given name. The function
663 ** first looks at the _LOADED table and, if that fails, try a
664 ** global variable with that name. In any case, leaves on the stack
667 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
669 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
670 lua_getfield(L, -1, modname); /* get _LOADED[modname] */
671 if (!lua_istable(L, -1)) { /* not found? */
672 lua_pop(L, 1); /* remove previous result */
673 /* try global variable (and create one if it does not exist) */
674 lua_pushglobaltable(L);
675 if (luaL_findtable(L, 0, modname, sizehint) != NULL)
676 luaL_error(L, "name conflict for module " LUA_QS, modname);
677 lua_pushvalue(L, -1);
678 lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
680 lua_remove(L, -2); /* remove _LOADED table */
684 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
685 const luaL_Reg *l, int nup) {
686 luaL_checkversion(L);
688 luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
689 lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
692 luaL_setfuncs(L, l, nup);
694 lua_pop(L, nup); /* remove upvalues */
698 /* }====================================================== */
701 ** set functions from list 'l' into table at top - 'nup'; each
702 ** function gets the 'nup' elements at the top as upvalues.
703 ** Returns with only the table at the stack.
705 LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
706 luaL_checkversion(L);
707 luaL_checkstack(L, nup, "too many upvalues");
708 for (; l->name != NULL; l++) { /* fill the table with given functions */
710 for (i = 0; i < nup; i++) /* copy upvalues to the top */
711 lua_pushvalue(L, -nup);
712 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
713 lua_setfield(L, -(nup + 2), l->name);
715 lua_pop(L, nup); /* remove upvalues */
720 ** ensure that stack[idx][fname] has a table and push that table
723 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
724 lua_getfield(L, idx, fname);
725 if (lua_istable(L, -1)) return 1; /* table already there */
727 lua_pop(L, 1); /* remove previous result */
728 idx = lua_absindex(L, idx);
730 lua_pushvalue(L, -1); /* copy to be left at top */
731 lua_setfield(L, idx, fname); /* assign new table to field */
732 return 0; /* false, because did not find table there */
738 ** stripped-down 'require'. Calls 'openf' to open a module,
739 ** registers the result in 'package.loaded' table and, if 'glb'
740 ** is true, also registers the result in the global table.
741 ** Leaves resulting module on the top.
743 LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
744 lua_CFunction openf, int glb) {
745 lua_pushcfunction(L, openf);
746 lua_pushstring(L, modname); /* argument to open function */
747 lua_call(L, 1, 1); /* open module */
748 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
749 lua_pushvalue(L, -2); /* make copy of module (call result) */
750 lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
751 lua_pop(L, 1); /* remove _LOADED table */
753 lua_pushvalue(L, -1); /* copy of 'mod' */
754 lua_setglobal(L, modname); /* _G[modname] = module */
759 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
762 size_t l = strlen(p);
764 luaL_buffinit(L, &b);
765 while ((wild = strstr(s, p)) != NULL) {
766 luaL_addlstring(&b, s, wild - s); /* push prefix */
767 luaL_addstring(&b, r); /* push replacement in place of pattern */
768 s = wild + l; /* continue after `p' */
770 luaL_addstring(&b, s); /* push last suffix */
772 return lua_tostring(L, -1);
776 LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
777 const lua_Number *v = lua_version(L);
778 if (v != lua_version(NULL))
779 luaL_error(L, "multiple Lua VMs detected");
781 luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
783 /* check conversions number -> integer types */
784 lua_pushnumber(L, -(lua_Number)0x1234);
785 if (lua_tointeger(L, -1) != -0x1234 ||
786 lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234)
787 luaL_error(L, "bad conversion number->int;"
788 " must recompile Lua with proper settings");