xref: /illumos-gate/usr/src/uts/common/fs/zfs/lua/lauxlib.c (revision dfc115332c94a2f62058ac7f2bce7631fbd20b3d)
1 /*
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
5 */
6 
7 
8 #include <sys/zfs_context.h>
9 
10 /* This file uses only the official API of Lua.
11 ** Any function declared here could be written as an application function.
12 */
13 
14 #define lauxlib_c
15 #define LUA_LIB
16 
17 #include "lua.h"
18 
19 #include "lauxlib.h"
20 
21 
22 /*
23 ** {======================================================
24 ** Traceback
25 ** =======================================================
26 */
27 
28 
29 #define LEVELS1	12	/* size of the first part of the stack */
30 #define LEVELS2	10	/* size of the second part of the stack */
31 
32 
33 
34 /*
35 ** search for 'objidx' in table at index -1.
36 ** return 1 + string at top if find a good name.
37 */
findfield(lua_State * L,int objidx,int level)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) */
46         return 1;
47       }
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 */
52         lua_concat(L, 3);
53         return 1;
54       }
55     }
56     lua_pop(L, 1);  /* remove value */
57   }
58   return 0;  /* not found */
59 }
60 
61 
pushglobalfuncname(lua_State * L,lua_Debug * ar)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 */
69     return 1;
70   }
71   else {
72     lua_settop(L, top);  /* remove function and global table */
73     return 0;
74   }
75 }
76 
77 
pushfuncname(lua_State * L,lua_Debug * ar)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 */
87     }
88     else
89       lua_pushliteral(L, "?");
90   }
91   else
92     lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
93 }
94 
95 
countlevels(lua_State * L)96 static int countlevels (lua_State *L) {
97   lua_Debug ar;
98   int li = 1, le = 1;
99   /* find an upper bound */
100   while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
101   /* do a binary search */
102   while (li < le) {
103     int m = (li + le)/2;
104     if (lua_getstack(L, m, &ar)) li = m + 1;
105     else le = m;
106   }
107   return le - 1;
108 }
109 
110 
luaL_traceback(lua_State * L,lua_State * L1,const char * msg,int level)111 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
112                                 const char *msg, int level) {
113   lua_Debug ar;
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 */
123     }
124     else {
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);
131       if (ar.istailcall)
132         lua_pushliteral(L, "\n\t(...tail calls...)");
133       lua_concat(L, lua_gettop(L) - top);
134     }
135   }
136   lua_concat(L, lua_gettop(L) - top);
137 }
138 
139 /* }====================================================== */
140 
141 
142 /*
143 ** {======================================================
144 ** Error-report functions
145 ** =======================================================
146 */
147 
luaL_argerror(lua_State * L,int narg,const char * extramsg)148 LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
149   lua_Debug ar;
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)",
157                            ar.name, extramsg);
158   }
159   if (ar.name == NULL)
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);
163 }
164 
165 
typeerror(lua_State * L,int narg,const char * tname)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);
170 }
171 
172 
tag_error(lua_State * L,int narg,int tag)173 static void tag_error (lua_State *L, int narg, int tag) {
174   typeerror(L, narg, lua_typename(L, tag));
175 }
176 
177 
luaL_where(lua_State * L,int level)178 LUALIB_API void luaL_where (lua_State *L, int level) {
179   lua_Debug ar;
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);
184       return;
185     }
186   }
187   lua_pushliteral(L, "");  /* else, no information available... */
188 }
189 
190 
luaL_error(lua_State * L,const char * fmt,...)191 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
192   va_list argp;
193   va_start(argp, fmt);
194   luaL_where(L, 1);
195   lua_pushvfstring(L, fmt, argp);
196   va_end(argp);
197   lua_concat(L, 2);
198   return lua_error(L);
199 }
200 
201 
202 #if !defined(inspectstat)	/* { */
203 
204 #if defined(LUA_USE_POSIX)
205 
206 #include <sys/wait.h>
207 
208 /*
209 ** use appropriate macros to interpret 'pclose' return status
210 */
211 #define inspectstat(stat,what)  \
212    if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
213    else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
214 
215 #else
216 
217 #define inspectstat(stat,what)  /* no op */
218 
219 #endif
220 
221 #endif				/* } */
222 
223 
224 /* }====================================================== */
225 
226 
227 /*
228 ** {======================================================
229 ** Userdata's metatable manipulation
230 ** =======================================================
231 */
232 
luaL_newmetatable(lua_State * L,const char * tname)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 */
237   lua_pop(L, 1);
238   lua_newtable(L);  /* create metatable */
239   lua_pushvalue(L, -1);
240   lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
241   return 1;
242 }
243 
244 
luaL_setmetatable(lua_State * L,const char * tname)245 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
246   luaL_getmetatable(L, tname);
247   lua_setmetatable(L, -2);
248 }
249 
250 
luaL_testudata(lua_State * L,int ud,const char * tname)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 */
259       return p;
260     }
261   }
262   return NULL;  /* value is not a userdata with a metatable */
263 }
264 
265 
luaL_checkudata(lua_State * L,int ud,const char * tname)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);
269   return p;
270 }
271 
272 /* }====================================================== */
273 
274 
275 /*
276 ** {======================================================
277 ** Argument check functions
278 ** =======================================================
279 */
280 
luaL_checkoption(lua_State * L,int narg,const char * def,const char * const lst[])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);
285   int i;
286   for (i=0; lst[i]; i++)
287     if (strcmp(lst[i], name) == 0)
288       return i;
289   return luaL_argerror(L, narg,
290                        lua_pushfstring(L, "invalid option " LUA_QS, name));
291 }
292 
293 
luaL_checkstack(lua_State * L,int space,const char * msg)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)) {
298     if (msg)
299       luaL_error(L, "stack overflow (%s)", msg);
300     else
301       luaL_error(L, "stack overflow");
302   }
303 }
304 
305 
luaL_checktype(lua_State * L,int narg,int t)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);
309 }
310 
311 
luaL_checkany(lua_State * L,int narg)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");
315 }
316 
317 
luaL_checklstring(lua_State * L,int narg,size_t * len)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);
321   return s;
322 }
323 
324 
luaL_optlstring(lua_State * L,int narg,const char * def,size_t * len)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)) {
328     if (len)
329       *len = (def ? strlen(def) : 0);
330     return def;
331   }
332   else return luaL_checklstring(L, narg, len);
333 }
334 
335 
luaL_checknumber(lua_State * L,int narg)336 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
337   int isnum;
338   lua_Number d = lua_tonumberx(L, narg, &isnum);
339   if (!isnum)
340     tag_error(L, narg, LUA_TNUMBER);
341   return d;
342 }
343 
344 
luaL_optnumber(lua_State * L,int narg,lua_Number def)345 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
346   return luaL_opt(L, luaL_checknumber, narg, def);
347 }
348 
349 
luaL_checkinteger(lua_State * L,int narg)350 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
351   int isnum;
352   lua_Integer d = lua_tointegerx(L, narg, &isnum);
353   if (!isnum)
354     tag_error(L, narg, LUA_TNUMBER);
355   return d;
356 }
357 
358 
luaL_checkunsigned(lua_State * L,int narg)359 LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
360   int isnum;
361   lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
362   if (!isnum)
363     tag_error(L, narg, LUA_TNUMBER);
364   return d;
365 }
366 
367 
luaL_optinteger(lua_State * L,int narg,lua_Integer def)368 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
369                                                       lua_Integer def) {
370   return luaL_opt(L, luaL_checkinteger, narg, def);
371 }
372 
373 
luaL_optunsigned(lua_State * L,int narg,lua_Unsigned def)374 LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,
375                                                         lua_Unsigned def) {
376   return luaL_opt(L, luaL_checkunsigned, narg, def);
377 }
378 
379 /* }====================================================== */
380 
381 
382 /*
383 ** {======================================================
384 ** Generic Buffer manipulation
385 ** =======================================================
386 */
387 
388 /*
389 ** check whether buffer is using a userdata on the stack as a temporary
390 ** buffer
391 */
392 #define buffonstack(B)	((B)->b != (B)->initb)
393 
394 
395 /*
396 ** returns a pointer to a free area with at least 'sz' bytes
397 */
luaL_prepbuffsize(luaL_Buffer * B,size_t sz)398 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
399   lua_State *L = B->L;
400   if (B->size - B->n < sz) {  /* not enough space? */
401     char *newbuff;
402     size_t newsize = B->size * 2;  /* double buffer size */
403     if (newsize - B->n < sz)  /* not big enough? */
404       newsize = B->n + sz;
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));
411     if (buffonstack(B))
412       lua_remove(L, -2);  /* remove old buffer */
413     B->b = newbuff;
414     B->size = newsize;
415   }
416   return &B->b[B->n];
417 }
418 
419 
luaL_addlstring(luaL_Buffer * B,const char * s,size_t l)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));
423   luaL_addsize(B, l);
424 }
425 
426 
luaL_addstring(luaL_Buffer * B,const char * s)427 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
428   luaL_addlstring(B, s, strlen(s));
429 }
430 
431 
luaL_pushresult(luaL_Buffer * B)432 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
433   lua_State *L = B->L;
434   lua_pushlstring(L, B->b, B->n);
435   if (buffonstack(B))
436     lua_remove(L, -2);  /* remove old buffer */
437 }
438 
439 
luaL_pushresultsize(luaL_Buffer * B,size_t sz)440 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
441   luaL_addsize(B, sz);
442   luaL_pushresult(B);
443 }
444 
445 
luaL_addvalue(luaL_Buffer * B)446 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
447   lua_State *L = B->L;
448   size_t l;
449   const char *s = lua_tolstring(L, -1, &l);
450   if (buffonstack(B))
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 */
454 }
455 
456 
luaL_buffinit(lua_State * L,luaL_Buffer * B)457 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
458   B->L = L;
459   B->b = B->initb;
460   B->n = 0;
461   B->size = LUAL_BUFFERSIZE;
462 }
463 
464 
luaL_buffinitsize(lua_State * L,luaL_Buffer * B,size_t sz)465 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
466   luaL_buffinit(L, B);
467   return luaL_prepbuffsize(B, sz);
468 }
469 
470 /* }====================================================== */
471 
472 
473 /*
474 ** {======================================================
475 ** Reference system
476 ** =======================================================
477 */
478 
479 /* index of free-list header */
480 #define freelist	0
481 
482 
luaL_ref(lua_State * L,int t)483 LUALIB_API int luaL_ref (lua_State *L, int t) {
484   int ref;
485   if (lua_isnil(L, -1)) {
486     lua_pop(L, 1);  /* remove from stack */
487     return LUA_REFNIL;  /* `nil' has a unique fixed reference */
488   }
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]) */
496   }
497   else  /* no free elements */
498     ref = (int)lua_rawlen(L, t) + 1;  /* get a new reference */
499   lua_rawseti(L, t, ref);
500   return ref;
501 }
502 
503 
luaL_unref(lua_State * L,int t,int ref)504 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
505   if (ref >= 0) {
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 */
511   }
512 }
513 
514 /* }====================================================== */
515 
516 
517 /*
518 ** {======================================================
519 ** Load functions
520 ** =======================================================
521 */
522 
523 typedef struct LoadS {
524   const char *s;
525   size_t size;
526 } LoadS;
527 
528 
getS(lua_State * L,void * ud,size_t * size)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;
533   *size = ls->size;
534   ls->size = 0;
535   return ls->s;
536 }
537 
538 
luaL_loadbufferx(lua_State * L,const char * buff,size_t size,const char * name,const char * mode)539 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
540                                  const char *name, const char *mode) {
541   LoadS ls;
542   ls.s = buff;
543   ls.size = size;
544   return lua_load(L, getS, &ls, name, mode);
545 }
546 
547 
luaL_loadstring(lua_State * L,const char * s)548 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
549   return luaL_loadbuffer(L, s, strlen(s), s);
550 }
551 
552 /* }====================================================== */
553 
554 
555 
luaL_getmetafield(lua_State * L,int obj,const char * event)556 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
557   if (!lua_getmetatable(L, obj))  /* no metatable? */
558     return 0;
559   lua_pushstring(L, event);
560   lua_rawget(L, -2);
561   if (lua_isnil(L, -1)) {
562     lua_pop(L, 2);  /* remove metatable and metafield */
563     return 0;
564   }
565   else {
566     lua_remove(L, -2);  /* remove only metatable */
567     return 1;
568   }
569 }
570 
571 
luaL_callmeta(lua_State * L,int obj,const char * event)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? */
575     return 0;
576   lua_pushvalue(L, obj);
577   lua_call(L, 1, 1);
578   return 1;
579 }
580 
581 
luaL_len(lua_State * L,int idx)582 LUALIB_API int luaL_len (lua_State *L, int idx) {
583   int l;
584   int isnum;
585   lua_len(L, idx);
586   l = (int)lua_tointegerx(L, -1, &isnum);
587   if (!isnum)
588     luaL_error(L, "object length is not a number");
589   lua_pop(L, 1);  /* remove object */
590   return l;
591 }
592 
593 
luaL_tolstring(lua_State * L,int idx,size_t * len)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)) {
597       case LUA_TNUMBER:
598       case LUA_TSTRING:
599         lua_pushvalue(L, idx);
600         break;
601       case LUA_TBOOLEAN:
602         lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
603         break;
604       case LUA_TNIL:
605         lua_pushliteral(L, "nil");
606         break;
607       default:
608         lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
609                                             lua_topointer(L, idx));
610         break;
611     }
612   }
613   return lua_tolstring(L, -1, len);
614 }
615 
616 
617 /*
618 ** {======================================================
619 ** Compatibility with 5.1 module functions
620 ** =======================================================
621 */
622 #if defined(LUA_COMPAT_MODULE)
623 
luaL_findtable(lua_State * L,int idx,const char * fname,int szhint)624 static const char *luaL_findtable (lua_State *L, int idx,
625                                    const char *fname, int szhint) {
626   const char *e;
627   if (idx) lua_pushvalue(L, idx);
628   do {
629     e = strchr(fname, '.');
630     if (e == NULL) e = fname + strlen(fname);
631     lua_pushlstring(L, fname, e - fname);
632     lua_rawget(L, -2);
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 */
639     }
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 */
643     }
644     lua_remove(L, -2);  /* remove previous table */
645     fname = e + 1;
646   } while (*e == '.');
647   return NULL;
648 }
649 
650 
651 /*
652 ** Count number of elements in a luaL_Reg list.
653 */
libsize(const luaL_Reg * l)654 static int libsize (const luaL_Reg *l) {
655   int size = 0;
656   for (; l && l->name; l++) size++;
657   return size;
658 }
659 
660 
661 /*
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
665 ** the module table.
666 */
luaL_pushmodule(lua_State * L,const char * modname,int sizehint)667 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
668                                  int sizehint) {
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 */
679   }
680   lua_remove(L, -2);  /* remove _LOADED table */
681 }
682 
683 
luaL_openlib(lua_State * L,const char * libname,const luaL_Reg * l,int nup)684 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
685                                const luaL_Reg *l, int nup) {
686   luaL_checkversion(L);
687   if (libname) {
688     luaL_pushmodule(L, libname, libsize(l));  /* get/create library table */
689     lua_insert(L, -(nup + 1));  /* move library table to below upvalues */
690   }
691   if (l)
692     luaL_setfuncs(L, l, nup);
693   else
694     lua_pop(L, nup);  /* remove upvalues */
695 }
696 
697 #endif
698 /* }====================================================== */
699 
700 /*
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.
704 */
luaL_setfuncs(lua_State * L,const luaL_Reg * l,int nup)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 */
709     int i;
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);
714   }
715   lua_pop(L, nup);  /* remove upvalues */
716 }
717 
718 
719 /*
720 ** ensure that stack[idx][fname] has a table and push that table
721 ** into the stack
722 */
luaL_getsubtable(lua_State * L,int idx,const char * fname)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 */
726   else {
727     lua_pop(L, 1);  /* remove previous result */
728     idx = lua_absindex(L, idx);
729     lua_newtable(L);
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 */
733   }
734 }
735 
736 
737 /*
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.
742 */
luaL_requiref(lua_State * L,const char * modname,lua_CFunction openf,int glb)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 */
752   if (glb) {
753     lua_pushvalue(L, -1);  /* copy of 'mod' */
754     lua_setglobal(L, modname);  /* _G[modname] = module */
755   }
756 }
757 
758 
luaL_gsub(lua_State * L,const char * s,const char * p,const char * r)759 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
760                                                                const char *r) {
761   const char *wild;
762   size_t l = strlen(p);
763   luaL_Buffer b;
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' */
769   }
770   luaL_addstring(&b, s);  /* push last suffix */
771   luaL_pushresult(&b);
772   return lua_tostring(L, -1);
773 }
774 
775 
luaL_checkversion_(lua_State * L,lua_Number ver)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");
780   else if (*v != ver)
781     luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
782                   ver, *v);
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");
789   lua_pop(L, 1);
790 }
791 
792