interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / lauxlib.c

1215 lines · 36295 bytes Raw Blame History
1/*
2** $Id: lauxlib.c $
3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h
5*/
6
7#define lauxlib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <errno.h>
14#include <stdarg.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18
19
20/*
21** This file uses only the official API of Lua.
22** Any function declared here could be written as an application function.
23*/
24
25#include "lua.h"
26
27#include "lauxlib.h"
28#include "llimits.h"
29
30
31/*
32** {======================================================
33** Traceback
34** =======================================================
35*/
36
37
38#define LEVELS1 10 /* size of the first part of the stack */
39#define LEVELS2 11 /* size of the second part of the stack */
40
41
42
43/*
44** Search for 'objidx' in table at index -1. ('objidx' must be an
45** absolute index.) Return 1 + string at top if it found a good name.
46*/
47static int findfield (lua_State *L, int objidx, int level) {
48 if (level == 0 || !lua_istable(L, -1))
49 return 0; /* not found */
50 lua_pushnil(L); /* start 'next' loop */
51 while (lua_next(L, -2)) { /* for each pair in table */
52 if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
53 if (lua_rawequal(L, objidx, -1)) { /* found object? */
54 lua_pop(L, 1); /* remove value (but keep name) */
55 return 1;
56 }
57 else if (findfield(L, objidx, level - 1)) { /* try recursively */
58 /* stack: lib_name, lib_table, field_name (top) */
59 lua_pushliteral(L, "."); /* place '.' between the two names */
60 lua_replace(L, -3); /* (in the slot occupied by table) */
61 lua_concat(L, 3); /* lib_name.field_name */
62 return 1;
63 }
64 }
65 lua_pop(L, 1); /* remove value */
66 }
67 return 0; /* not found */
68}
69
70
71/*
72** Search for a name for a function in all loaded modules
73*/
74static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
75 int top = lua_gettop(L);
76 lua_getinfo(L, "f", ar); /* push function */
77 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
78 luaL_checkstack(L, 6, "not enough stack"); /* slots for 'findfield' */
79 if (findfield(L, top + 1, 2)) {
80 const char *name = lua_tostring(L, -1);
81 if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */
82 lua_pushstring(L, name + 3); /* push name without prefix */
83 lua_remove(L, -2); /* remove original name */
84 }
85 lua_copy(L, -1, top + 1); /* copy name to proper place */
86 lua_settop(L, top + 1); /* remove table "loaded" and name copy */
87 return 1;
88 }
89 else {
90 lua_settop(L, top); /* remove function and global table */
91 return 0;
92 }
93}
94
95
96static void pushfuncname (lua_State *L, lua_Debug *ar) {
97 if (*ar->namewhat != '\0') /* is there a name from code? */
98 lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
99 else if (*ar->what == 'm') /* main? */
100 lua_pushliteral(L, "main chunk");
101 else if (pushglobalfuncname(L, ar)) { /* try a global name */
102 lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
103 lua_remove(L, -2); /* remove name */
104 }
105 else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
106 lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
107 else /* nothing left... */
108 lua_pushliteral(L, "?");
109}
110
111
112static int lastlevel (lua_State *L) {
113 lua_Debug ar;
114 int li = 1, le = 1;
115 /* find an upper bound */
116 while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
117 /* do a binary search */
118 while (li < le) {
119 int m = (li + le)/2;
120 if (lua_getstack(L, m, &ar)) li = m + 1;
121 else le = m;
122 }
123 return le - 1;
124}
125
126
127LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
128 const char *msg, int level) {
129 luaL_Buffer b;
130 lua_Debug ar;
131 int last = lastlevel(L1);
132 int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
133 luaL_buffinit(L, &b);
134 if (msg) {
135 luaL_addstring(&b, msg);
136 luaL_addchar(&b, '\n');
137 }
138 luaL_addstring(&b, "stack traceback:");
139 while (lua_getstack(L1, level++, &ar)) {
140 if (limit2show-- == 0) { /* too many levels? */
141 int n = last - level - LEVELS2 + 1; /* number of levels to skip */
142 lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n);
143 luaL_addvalue(&b); /* add warning about skip */
144 level += n; /* and skip to last levels */
145 }
146 else {
147 lua_getinfo(L1, "Slnt", &ar);
148 if (ar.currentline <= 0)
149 lua_pushfstring(L, "\n\t%s: in ", ar.short_src);
150 else
151 lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline);
152 luaL_addvalue(&b);
153 pushfuncname(L, &ar);
154 luaL_addvalue(&b);
155 if (ar.istailcall)
156 luaL_addstring(&b, "\n\t(...tail calls...)");
157 }
158 }
159 luaL_pushresult(&b);
160}
161
162/* }====================================================== */
163
164
165/*
166** {======================================================
167** Error-report functions
168** =======================================================
169*/
170
171LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
172 lua_Debug ar;
173 const char *argword;
174 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
175 return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
176 lua_getinfo(L, "nt", &ar);
177 if (arg <= ar.extraargs) /* error in an extra argument? */
178 argword = "extra argument";
179 else {
180 arg -= ar.extraargs; /* do not count extra arguments */
181 if (strcmp(ar.namewhat, "method") == 0) { /* colon syntax? */
182 arg--; /* do not count (extra) self argument */
183 if (arg == 0) /* error in self argument? */
184 return luaL_error(L, "calling '%s' on bad self (%s)",
185 ar.name, extramsg);
186 /* else go through; error in a regular argument */
187 }
188 argword = "argument";
189 }
190 if (ar.name == NULL)
191 ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
192 return luaL_error(L, "bad %s #%d to '%s' (%s)",
193 argword, arg, ar.name, extramsg);
194}
195
196
197LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
198 const char *msg;
199 const char *typearg; /* name for the type of the actual argument */
200 if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
201 typearg = lua_tostring(L, -1); /* use the given type name */
202 else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
203 typearg = "light userdata"; /* special name for messages */
204 else
205 typearg = luaL_typename(L, arg); /* standard name */
206 msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
207 return luaL_argerror(L, arg, msg);
208}
209
210
211static void tag_error (lua_State *L, int arg, int tag) {
212 luaL_typeerror(L, arg, lua_typename(L, tag));
213}
214
215
216/*
217** The use of 'lua_pushfstring' ensures this function does not
218** need reserved stack space when called.
219*/
220LUALIB_API void luaL_where (lua_State *L, int level) {
221 lua_Debug ar;
222 if (lua_getstack(L, level, &ar)) { /* check function at level */
223 lua_getinfo(L, "Sl", &ar); /* get info about it */
224 if (ar.currentline > 0) { /* is there info? */
225 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
226 return;
227 }
228 }
229 lua_pushfstring(L, ""); /* else, no information available... */
230}
231
232
233/*
234** Again, the use of 'lua_pushvfstring' ensures this function does
235** not need reserved stack space when called. (At worst, it generates
236** a memory error instead of the given message.)
237*/
238LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
239 va_list argp;
240 va_start(argp, fmt);
241 luaL_where(L, 1);
242 lua_pushvfstring(L, fmt, argp);
243 va_end(argp);
244 lua_concat(L, 2);
245 return lua_error(L);
246}
247
248
249LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
250 int en = errno; /* calls to Lua API may change this value */
251 if (stat) {
252 lua_pushboolean(L, 1);
253 return 1;
254 }
255 else {
256 const char *msg;
257 luaL_pushfail(L);
258 msg = (en != 0) ? strerror(en) : "(no extra info)";
259 if (fname)
260 lua_pushfstring(L, "%s: %s", fname, msg);
261 else
262 lua_pushstring(L, msg);
263 lua_pushinteger(L, en);
264 return 3;
265 }
266}
267
268
269#if !defined(l_inspectstat) /* { */
270
271#if defined(LUA_USE_POSIX)
272
273#include <sys/wait.h>
274
275/*
276** use appropriate macros to interpret 'pclose' return status
277*/
278#define l_inspectstat(stat,what) \
279 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
280 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
281
282#else
283
284#define l_inspectstat(stat,what) /* no op */
285
286#endif
287
288#endif /* } */
289
290
291LUALIB_API int luaL_execresult (lua_State *L, int stat) {
292 if (stat != 0 && errno != 0) /* error with an 'errno'? */
293 return luaL_fileresult(L, 0, NULL);
294 else {
295 const char *what = "exit"; /* type of termination */
296 l_inspectstat(stat, what); /* interpret result */
297 if (*what == 'e' && stat == 0) /* successful termination? */
298 lua_pushboolean(L, 1);
299 else
300 luaL_pushfail(L);
301 lua_pushstring(L, what);
302 lua_pushinteger(L, stat);
303 return 3; /* return true/fail,what,code */
304 }
305}
306
307/* }====================================================== */
308
309
310
311/*
312** {======================================================
313** Userdata's metatable manipulation
314** =======================================================
315*/
316
317LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
318 if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
319 return 0; /* leave previous value on top, but return 0 */
320 lua_pop(L, 1);
321 lua_createtable(L, 0, 2); /* create metatable */
322 lua_pushstring(L, tname);
323 lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
324 lua_pushvalue(L, -1);
325 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
326 return 1;
327}
328
329
330LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
331 luaL_getmetatable(L, tname);
332 lua_setmetatable(L, -2);
333}
334
335
336LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
337 void *p = lua_touserdata(L, ud);
338 if (p != NULL) { /* value is a userdata? */
339 if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
340 luaL_getmetatable(L, tname); /* get correct metatable */
341 if (!lua_rawequal(L, -1, -2)) /* not the same? */
342 p = NULL; /* value is a userdata with wrong metatable */
343 lua_pop(L, 2); /* remove both metatables */
344 return p;
345 }
346 }
347 return NULL; /* value is not a userdata with a metatable */
348}
349
350
351LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
352 void *p = luaL_testudata(L, ud, tname);
353 luaL_argexpected(L, p != NULL, ud, tname);
354 return p;
355}
356
357/* }====================================================== */
358
359
360/*
361** {======================================================
362** Argument check functions
363** =======================================================
364*/
365
366LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
367 const char *const lst[]) {
368 const char *name = (def) ? luaL_optstring(L, arg, def) :
369 luaL_checkstring(L, arg);
370 int i;
371 for (i=0; lst[i]; i++)
372 if (strcmp(lst[i], name) == 0)
373 return i;
374 return luaL_argerror(L, arg,
375 lua_pushfstring(L, "invalid option '%s'", name));
376}
377
378
379/*
380** Ensures the stack has at least 'space' extra slots, raising an error
381** if it cannot fulfill the request. (The error handling needs a few
382** extra slots to format the error message. In case of an error without
383** this extra space, Lua will generate the same 'stack overflow' error,
384** but without 'msg'.)
385*/
386LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
387 if (l_unlikely(!lua_checkstack(L, space))) {
388 if (msg)
389 luaL_error(L, "stack overflow (%s)", msg);
390 else
391 luaL_error(L, "stack overflow");
392 }
393}
394
395
396LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
397 if (l_unlikely(lua_type(L, arg) != t))
398 tag_error(L, arg, t);
399}
400
401
402LUALIB_API void luaL_checkany (lua_State *L, int arg) {
403 if (l_unlikely(lua_type(L, arg) == LUA_TNONE))
404 luaL_argerror(L, arg, "value expected");
405}
406
407
408LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
409 const char *s = lua_tolstring(L, arg, len);
410 if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING);
411 return s;
412}
413
414
415LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
416 const char *def, size_t *len) {
417 if (lua_isnoneornil(L, arg)) {
418 if (len)
419 *len = (def ? strlen(def) : 0);
420 return def;
421 }
422 else return luaL_checklstring(L, arg, len);
423}
424
425
426LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
427 int isnum;
428 lua_Number d = lua_tonumberx(L, arg, &isnum);
429 if (l_unlikely(!isnum))
430 tag_error(L, arg, LUA_TNUMBER);
431 return d;
432}
433
434
435LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
436 return luaL_opt(L, luaL_checknumber, arg, def);
437}
438
439
440static void interror (lua_State *L, int arg) {
441 if (lua_isnumber(L, arg))
442 luaL_argerror(L, arg, "number has no integer representation");
443 else
444 tag_error(L, arg, LUA_TNUMBER);
445}
446
447
448LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
449 int isnum;
450 lua_Integer d = lua_tointegerx(L, arg, &isnum);
451 if (l_unlikely(!isnum)) {
452 interror(L, arg);
453 }
454 return d;
455}
456
457
458LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
459 lua_Integer def) {
460 return luaL_opt(L, luaL_checkinteger, arg, def);
461}
462
463/* }====================================================== */
464
465
466/*
467** {======================================================
468** Generic Buffer manipulation
469** =======================================================
470*/
471
472/* userdata to box arbitrary data */
473typedef struct UBox {
474 void *box;
475 size_t bsize;
476} UBox;
477
478
479/* Resize the buffer used by a box. Optimize for the common case of
480** resizing to the old size. (For instance, __gc will resize the box
481** to 0 even after it was closed. 'pushresult' may also resize it to a
482** final size that is equal to the one set when the buffer was created.)
483*/
484static void *resizebox (lua_State *L, int idx, size_t newsize) {
485 UBox *box = (UBox *)lua_touserdata(L, idx);
486 if (box->bsize == newsize) /* not changing size? */
487 return box->box; /* keep the buffer */
488 else {
489 void *ud;
490 lua_Alloc allocf = lua_getallocf(L, &ud);
491 void *temp = allocf(ud, box->box, box->bsize, newsize);
492 if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */
493 lua_pushliteral(L, "not enough memory");
494 lua_error(L); /* raise a memory error */
495 }
496 box->box = temp;
497 box->bsize = newsize;
498 return temp;
499 }
500}
501
502
503static int boxgc (lua_State *L) {
504 resizebox(L, 1, 0);
505 return 0;
506}
507
508
509static const luaL_Reg boxmt[] = { /* box metamethods */
510 {"__gc", boxgc},
511 {"__close", boxgc},
512 {NULL, NULL}
513};
514
515
516/*
517** Get/create metatable (MT) for boxes
518*/
519static void getBoxMT (lua_State *L) {
520 const char *BOXMT = "_UBOX*"; /* key for the metatable */
521 if (luaL_getmetatable(L, BOXMT) == LUA_TNIL) { /* MT not created yet? */
522 luaL_newlibtable(L, boxmt); /* create it */
523 luaL_setfuncs(L, boxmt, 0); /* initialize it */
524 lua_copy(L, -1, -2); /* change stack from nil,MT to MT,MT */
525 lua_setfield(L, LUA_REGISTRYINDEX, BOXMT); /* store MT in the registry */
526 }
527}
528
529
530static void newbox (lua_State *L) {
531 UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);
532 box->box = NULL;
533 box->bsize = 0;
534 getBoxMT(L);
535 lua_setmetatable(L, -2);
536}
537
538
539/*
540** check whether buffer is using a userdata on the stack as a temporary
541** buffer
542*/
543#define buffonstack(B) ((B)->b != (B)->init.b)
544
545
546/*
547** Whenever buffer is accessed, slot 'idx' must either be a box (which
548** cannot be NULL) or it is a placeholder for the buffer.
549*/
550#define checkbufferlevel(B,idx) \
551 lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \
552 : lua_touserdata(B->L, idx) == (void*)B)
553
554
555/*
556** Compute new size for buffer 'B', enough to accommodate extra 'sz'
557** bytes plus one for a terminating zero.
558*/
559static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
560 size_t newsize = B->size;
561 if (l_unlikely(sz >= MAX_SIZE - B->n))
562 return cast_sizet(luaL_error(B->L, "resulting string too large"));
563 /* else B->n + sz + 1 <= MAX_SIZE */
564 if (newsize <= MAX_SIZE/3 * 2) /* no overflow? */
565 newsize += (newsize >> 1); /* new size *= 1.5 */
566 if (newsize < B->n + sz + 1) /* not big enough? */
567 newsize = B->n + sz + 1;
568 return newsize;
569}
570
571
572/*
573** Returns a pointer to a free area with at least 'sz' bytes in buffer
574** 'B'. 'boxidx' is the relative position in the stack where is the
575** buffer's box or its placeholder.
576*/
577static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
578 checkbufferlevel(B, boxidx);
579 if (B->size - B->n >= sz) /* enough space? */
580 return B->b + B->n;
581 else {
582 lua_State *L = B->L;
583 char *newbuff;
584 size_t newsize = newbuffsize(B, sz);
585 /* create larger buffer */
586 if (buffonstack(B)) /* buffer already has a box? */
587 newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */
588 else { /* no box yet */
589 lua_remove(L, boxidx); /* remove placeholder */
590 newbox(L); /* create a new box */
591 lua_insert(L, boxidx); /* move box to its intended position */
592 lua_toclose(L, boxidx);
593 newbuff = (char *)resizebox(L, boxidx, newsize);
594 memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
595 }
596 B->b = newbuff;
597 B->size = newsize;
598 return newbuff + B->n;
599 }
600}
601
602/*
603** returns a pointer to a free area with at least 'sz' bytes
604*/
605LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
606 return prepbuffsize(B, sz, -1);
607}
608
609
610LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
611 if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
612 char *b = prepbuffsize(B, l, -1);
613 memcpy(b, s, l * sizeof(char));
614 luaL_addsize(B, l);
615 }
616}
617
618
619LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
620 luaL_addlstring(B, s, strlen(s));
621}
622
623
624LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
625 lua_State *L = B->L;
626 checkbufferlevel(B, -1);
627 if (!buffonstack(B)) /* using static buffer? */
628 lua_pushlstring(L, B->b, B->n); /* save result as regular string */
629 else { /* reuse buffer already allocated */
630 UBox *box = (UBox *)lua_touserdata(L, -1);
631 void *ud;
632 lua_Alloc allocf = lua_getallocf(L, &ud); /* function to free buffer */
633 size_t len = B->n; /* final string length */
634 char *s;
635 resizebox(L, -1, len + 1); /* adjust box size to content size */
636 s = (char*)box->box; /* final buffer address */
637 s[len] = '\0'; /* add ending zero */
638 /* clear box, as Lua will take control of the buffer */
639 box->bsize = 0; box->box = NULL;
640 lua_pushexternalstring(L, s, len, allocf, ud);
641 lua_closeslot(L, -2); /* close the box */
642 lua_gc(L, LUA_GCSTEP, len);
643 }
644 lua_remove(L, -2); /* remove box or placeholder from the stack */
645}
646
647
648LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
649 luaL_addsize(B, sz);
650 luaL_pushresult(B);
651}
652
653
654/*
655** 'luaL_addvalue' is the only function in the Buffer system where the
656** box (if existent) is not on the top of the stack. So, instead of
657** calling 'luaL_addlstring', it replicates the code using -2 as the
658** last argument to 'prepbuffsize', signaling that the box is (or will
659** be) below the string being added to the buffer. (Box creation can
660** trigger an emergency GC, so we should not remove the string from the
661** stack before we have the space guaranteed.)
662*/
663LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
664 lua_State *L = B->L;
665 size_t len;
666 const char *s = lua_tolstring(L, -1, &len);
667 char *b = prepbuffsize(B, len, -2);
668 memcpy(b, s, len * sizeof(char));
669 luaL_addsize(B, len);
670 lua_pop(L, 1); /* pop string */
671}
672
673
674LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
675 B->L = L;
676 B->b = B->init.b;
677 B->n = 0;
678 B->size = LUAL_BUFFERSIZE;
679 lua_pushlightuserdata(L, (void*)B); /* push placeholder */
680}
681
682
683LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
684 luaL_buffinit(L, B);
685 return prepbuffsize(B, sz, -1);
686}
687
688/* }====================================================== */
689
690
691/*
692** {======================================================
693** Reference system
694** =======================================================
695*/
696
697/*
698** The previously freed references form a linked list: t[1] is the index
699** of a first free index, t[t[1]] is the index of the second element,
700** etc. A zero signals the end of the list.
701*/
702LUALIB_API int luaL_ref (lua_State *L, int t) {
703 int ref;
704 if (lua_isnil(L, -1)) {
705 lua_pop(L, 1); /* remove from stack */
706 return LUA_REFNIL; /* 'nil' has a unique fixed reference */
707 }
708 t = lua_absindex(L, t);
709 if (lua_rawgeti(L, t, 1) == LUA_TNUMBER) /* already initialized? */
710 ref = (int)lua_tointeger(L, -1); /* ref = t[1] */
711 else { /* first access */
712 lua_assert(!lua_toboolean(L, -1)); /* must be nil or false */
713 ref = 0; /* list is empty */
714 lua_pushinteger(L, 0); /* initialize as an empty list */
715 lua_rawseti(L, t, 1); /* ref = t[1] = 0 */
716 }
717 lua_pop(L, 1); /* remove element from stack */
718 if (ref != 0) { /* any free element? */
719 lua_rawgeti(L, t, ref); /* remove it from list */
720 lua_rawseti(L, t, 1); /* (t[1] = t[ref]) */
721 }
722 else /* no free elements */
723 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
724 lua_rawseti(L, t, ref);
725 return ref;
726}
727
728
729LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
730 if (ref >= 0) {
731 t = lua_absindex(L, t);
732 lua_rawgeti(L, t, 1);
733 lua_assert(lua_isinteger(L, -1));
734 lua_rawseti(L, t, ref); /* t[ref] = t[1] */
735 lua_pushinteger(L, ref);
736 lua_rawseti(L, t, 1); /* t[1] = ref */
737 }
738}
739
740/* }====================================================== */
741
742
743/*
744** {======================================================
745** Load functions
746** =======================================================
747*/
748
749typedef struct LoadF {
750 unsigned n; /* number of pre-read characters */
751 FILE *f; /* file being read */
752 char buff[BUFSIZ]; /* area for reading file */
753} LoadF;
754
755
756static const char *getF (lua_State *L, void *ud, size_t *size) {
757 LoadF *lf = (LoadF *)ud;
758 UNUSED(L);
759 if (lf->n > 0) { /* are there pre-read characters to be read? */
760 *size = lf->n; /* return them (chars already in buffer) */
761 lf->n = 0; /* no more pre-read characters */
762 }
763 else { /* read a block from file */
764 /* 'fread' can return > 0 *and* set the EOF flag. If next call to
765 'getF' called 'fread', it might still wait for user input.
766 The next check avoids this problem. */
767 if (feof(lf->f)) return NULL;
768 *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
769 }
770 return lf->buff;
771}
772
773
774static int errfile (lua_State *L, const char *what, int fnameindex) {
775 int err = errno;
776 const char *filename = lua_tostring(L, fnameindex) + 1;
777 if (err != 0)
778 lua_pushfstring(L, "cannot %s %s: %s", what, filename, strerror(err));
779 else
780 lua_pushfstring(L, "cannot %s %s", what, filename);
781 lua_remove(L, fnameindex);
782 return LUA_ERRFILE;
783}
784
785
786/*
787** Skip an optional BOM at the start of a stream. If there is an
788** incomplete BOM (the first character is correct but the rest is
789** not), returns the first character anyway to force an error
790** (as no chunk can start with 0xEF).
791*/
792static int skipBOM (FILE *f) {
793 int c = getc(f); /* read first character */
794 if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF) /* correct BOM? */
795 return getc(f); /* ignore BOM and return next char */
796 else /* no (valid) BOM */
797 return c; /* return first character */
798}
799
800
801/*
802** reads the first character of file 'f' and skips an optional BOM mark
803** in its beginning plus its first line if it starts with '#'. Returns
804** true if it skipped the first line. In any case, '*cp' has the
805** first "valid" character of the file (after the optional BOM and
806** a first-line comment).
807*/
808static int skipcomment (FILE *f, int *cp) {
809 int c = *cp = skipBOM(f);
810 if (c == '#') { /* first line is a comment (Unix exec. file)? */
811 do { /* skip first line */
812 c = getc(f);
813 } while (c != EOF && c != '\n');
814 *cp = getc(f); /* next character after comment, if present */
815 return 1; /* there was a comment */
816 }
817 else return 0; /* no comment */
818}
819
820
821LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
822 const char *mode) {
823 LoadF lf;
824 int status, readstatus;
825 int c;
826 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
827 if (filename == NULL) {
828 lua_pushliteral(L, "=stdin");
829 lf.f = stdin;
830 }
831 else {
832 lua_pushfstring(L, "@%s", filename);
833 errno = 0;
834 lf.f = fopen(filename, "r");
835 if (lf.f == NULL) return errfile(L, "open", fnameindex);
836 }
837 lf.n = 0;
838 if (skipcomment(lf.f, &c)) /* read initial portion */
839 lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */
840 if (c == LUA_SIGNATURE[0]) { /* binary file? */
841 lf.n = 0; /* remove possible newline */
842 if (filename) { /* "real" file? */
843 errno = 0;
844 lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
845 if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
846 skipcomment(lf.f, &c); /* re-read initial portion */
847 }
848 }
849 if (c != EOF)
850 lf.buff[lf.n++] = cast_char(c); /* 'c' is the first character */
851 status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
852 readstatus = ferror(lf.f);
853 errno = 0; /* no useful error number until here */
854 if (filename) fclose(lf.f); /* close file (even in case of errors) */
855 if (readstatus) {
856 lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
857 return errfile(L, "read", fnameindex);
858 }
859 lua_remove(L, fnameindex);
860 return status;
861}
862
863
864typedef struct LoadS {
865 const char *s;
866 size_t size;
867} LoadS;
868
869
870static const char *getS (lua_State *L, void *ud, size_t *size) {
871 LoadS *ls = (LoadS *)ud;
872 UNUSED(L);
873 if (ls->size == 0) return NULL;
874 *size = ls->size;
875 ls->size = 0;
876 return ls->s;
877}
878
879
880LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
881 const char *name, const char *mode) {
882 LoadS ls;
883 ls.s = buff;
884 ls.size = size;
885 return lua_load(L, getS, &ls, name, mode);
886}
887
888
889LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
890 return luaL_loadbufferx(L, s, strlen(s), s, "t");
891}
892
893/* }====================================================== */
894
895
896
897LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
898 if (!lua_getmetatable(L, obj)) /* no metatable? */
899 return LUA_TNIL;
900 else {
901 int tt;
902 lua_pushstring(L, event);
903 tt = lua_rawget(L, -2);
904 if (tt == LUA_TNIL) /* is metafield nil? */
905 lua_pop(L, 2); /* remove metatable and metafield */
906 else
907 lua_remove(L, -2); /* remove only metatable */
908 return tt; /* return metafield type */
909 }
910}
911
912
913LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
914 obj = lua_absindex(L, obj);
915 if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
916 return 0;
917 lua_pushvalue(L, obj);
918 lua_call(L, 1, 1);
919 return 1;
920}
921
922
923LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
924 lua_Integer l;
925 int isnum;
926 lua_len(L, idx);
927 l = lua_tointegerx(L, -1, &isnum);
928 if (l_unlikely(!isnum))
929 luaL_error(L, "object length is not an integer");
930 lua_pop(L, 1); /* remove object */
931 return l;
932}
933
934
935LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
936 idx = lua_absindex(L,idx);
937 if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
938 if (!lua_isstring(L, -1))
939 luaL_error(L, "'__tostring' must return a string");
940 }
941 else {
942 switch (lua_type(L, idx)) {
943 case LUA_TNUMBER: {
944 char buff[LUA_N2SBUFFSZ];
945 lua_numbertocstring(L, idx, buff);
946 lua_pushstring(L, buff);
947 break;
948 }
949 case LUA_TSTRING:
950 lua_pushvalue(L, idx);
951 break;
952 case LUA_TBOOLEAN:
953 lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
954 break;
955 case LUA_TNIL:
956 lua_pushliteral(L, "nil");
957 break;
958 default: {
959 int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
960 const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
961 luaL_typename(L, idx);
962 lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
963 if (tt != LUA_TNIL)
964 lua_remove(L, -2); /* remove '__name' */
965 break;
966 }
967 }
968 }
969 return lua_tolstring(L, -1, len);
970}
971
972
973/*
974** set functions from list 'l' into table at top - 'nup'; each
975** function gets the 'nup' elements at the top as upvalues.
976** Returns with only the table at the stack.
977*/
978LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
979 luaL_checkstack(L, nup, "too many upvalues");
980 for (; l->name != NULL; l++) { /* fill the table with given functions */
981 if (l->func == NULL) /* placeholder? */
982 lua_pushboolean(L, 0);
983 else {
984 int i;
985 for (i = 0; i < nup; i++) /* copy upvalues to the top */
986 lua_pushvalue(L, -nup);
987 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
988 }
989 lua_setfield(L, -(nup + 2), l->name);
990 }
991 lua_pop(L, nup); /* remove upvalues */
992}
993
994
995/*
996** ensure that stack[idx][fname] has a table and push that table
997** into the stack
998*/
999LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
1000 if (lua_getfield(L, idx, fname) == LUA_TTABLE)
1001 return 1; /* table already there */
1002 else {
1003 lua_pop(L, 1); /* remove previous result */
1004 idx = lua_absindex(L, idx);
1005 lua_newtable(L);
1006 lua_pushvalue(L, -1); /* copy to be left at top */
1007 lua_setfield(L, idx, fname); /* assign new table to field */
1008 return 0; /* false, because did not find table there */
1009 }
1010}
1011
1012
1013/*
1014** Stripped-down 'require': After checking "loaded" table, calls 'openf'
1015** to open a module, registers the result in 'package.loaded' table and,
1016** if 'glb' is true, also registers the result in the global table.
1017** Leaves resulting module on the top.
1018*/
1019LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
1020 lua_CFunction openf, int glb) {
1021 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
1022 lua_getfield(L, -1, modname); /* LOADED[modname] */
1023 if (!lua_toboolean(L, -1)) { /* package not already loaded? */
1024 lua_pop(L, 1); /* remove field */
1025 lua_pushcfunction(L, openf);
1026 lua_pushstring(L, modname); /* argument to open function */
1027 lua_call(L, 1, 1); /* call 'openf' to open module */
1028 lua_pushvalue(L, -1); /* make copy of module (call result) */
1029 lua_setfield(L, -3, modname); /* LOADED[modname] = module */
1030 }
1031 lua_remove(L, -2); /* remove LOADED table */
1032 if (glb) {
1033 lua_pushvalue(L, -1); /* copy of module */
1034 lua_setglobal(L, modname); /* _G[modname] = module */
1035 }
1036}
1037
1038
1039LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
1040 const char *p, const char *r) {
1041 const char *wild;
1042 size_t l = strlen(p);
1043 while ((wild = strstr(s, p)) != NULL) {
1044 luaL_addlstring(b, s, ct_diff2sz(wild - s)); /* push prefix */
1045 luaL_addstring(b, r); /* push replacement in place of pattern */
1046 s = wild + l; /* continue after 'p' */
1047 }
1048 luaL_addstring(b, s); /* push last suffix */
1049}
1050
1051
1052LUALIB_API const char *luaL_gsub (lua_State *L, const char *s,
1053 const char *p, const char *r) {
1054 luaL_Buffer b;
1055 luaL_buffinit(L, &b);
1056 luaL_addgsub(&b, s, p, r);
1057 luaL_pushresult(&b);
1058 return lua_tostring(L, -1);
1059}
1060
1061
1062void *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1063 UNUSED(ud); UNUSED(osize);
1064 if (nsize == 0) {
1065 free(ptr);
1066 return NULL;
1067 }
1068 else
1069 return realloc(ptr, nsize);
1070}
1071
1072
1073/*
1074** Standard panic function just prints an error message. The test
1075** with 'lua_type' avoids possible memory errors in 'lua_tostring'.
1076*/
1077static int panic (lua_State *L) {
1078 const char *msg = (lua_type(L, -1) == LUA_TSTRING)
1079 ? lua_tostring(L, -1)
1080 : "error object is not a string";
1081 lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
1082 msg);
1083 return 0; /* return to Lua to abort */
1084}
1085
1086
1087/*
1088** Warning functions:
1089** warnfoff: warning system is off
1090** warnfon: ready to start a new message
1091** warnfcont: previous message is to be continued
1092*/
1093static void warnfoff (void *ud, const char *message, int tocont);
1094static void warnfon (void *ud, const char *message, int tocont);
1095static void warnfcont (void *ud, const char *message, int tocont);
1096
1097
1098/*
1099** Check whether message is a control message. If so, execute the
1100** control or ignore it if unknown.
1101*/
1102static int checkcontrol (lua_State *L, const char *message, int tocont) {
1103 if (tocont || *(message++) != '@') /* not a control message? */
1104 return 0;
1105 else {
1106 if (strcmp(message, "off") == 0)
1107 lua_setwarnf(L, warnfoff, L); /* turn warnings off */
1108 else if (strcmp(message, "on") == 0)
1109 lua_setwarnf(L, warnfon, L); /* turn warnings on */
1110 return 1; /* it was a control message */
1111 }
1112}
1113
1114
1115static void warnfoff (void *ud, const char *message, int tocont) {
1116 checkcontrol((lua_State *)ud, message, tocont);
1117}
1118
1119
1120/*
1121** Writes the message and handle 'tocont', finishing the message
1122** if needed and setting the next warn function.
1123*/
1124static void warnfcont (void *ud, const char *message, int tocont) {
1125 lua_State *L = (lua_State *)ud;
1126 lua_writestringerror("%s", message); /* write message */
1127 if (tocont) /* not the last part? */
1128 lua_setwarnf(L, warnfcont, L); /* to be continued */
1129 else { /* last part */
1130 lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
1131 lua_setwarnf(L, warnfon, L); /* next call is a new message */
1132 }
1133}
1134
1135
1136static void warnfon (void *ud, const char *message, int tocont) {
1137 if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */
1138 return; /* nothing else to be done */
1139 lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
1140 warnfcont(ud, message, tocont); /* finish processing */
1141}
1142
1143
1144
1145/*
1146** A function to compute an unsigned int with some level of
1147** randomness. Rely on Address Space Layout Randomization (if present)
1148** and the current time.
1149*/
1150#if !defined(luai_makeseed)
1151
1152#include <time.h>
1153
1154
1155/* Size for the buffer, in bytes */
1156#define BUFSEEDB (sizeof(void*) + sizeof(time_t))
1157
1158/* Size for the buffer in int's, rounded up */
1159#define BUFSEED ((BUFSEEDB + sizeof(int) - 1) / sizeof(int))
1160
1161/*
1162** Copy the contents of variable 'v' into the buffer pointed by 'b'.
1163** (The '&b[0]' disguises 'b' to fix an absurd warning from clang.)
1164*/
1165#define addbuff(b,v) (memcpy(&b[0], &(v), sizeof(v)), b += sizeof(v))
1166
1167
1168static unsigned int luai_makeseed (void) {
1169 unsigned int buff[BUFSEED];
1170 unsigned int res;
1171 unsigned int i;
1172 time_t t = time(NULL);
1173 char *b = (char*)buff;
1174 addbuff(b, b); /* local variable's address */
1175 addbuff(b, t); /* time */
1176 /* fill (rare but possible) remain of the buffer with zeros */
1177 memset(b, 0, sizeof(buff) - BUFSEEDB);
1178 res = buff[0];
1179 for (i = 1; i < BUFSEED; i++)
1180 res ^= (res >> 3) + (res << 7) + buff[i];
1181 return res;
1182}
1183
1184#endif
1185
1186
1187LUALIB_API unsigned int luaL_makeseed (lua_State *L) {
1188 UNUSED(L);
1189 return luai_makeseed();
1190}
1191
1192
1193/*
1194** Use the name with parentheses so that headers can redefine it
1195** as a macro.
1196*/
1197LUALIB_API lua_State *(luaL_newstate) (void) {
1198 lua_State *L = lua_newstate(luaL_alloc, NULL, luaL_makeseed(NULL));
1199 if (l_likely(L)) {
1200 lua_atpanic(L, &panic);
1201 lua_setwarnf(L, warnfon, L);
1202 }
1203 return L;
1204}
1205
1206
1207LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
1208 lua_Number v = lua_version(L);
1209 if (sz != LUAL_NUMSIZES) /* check numeric types */
1210 luaL_error(L, "core and library have incompatible numeric types");
1211 else if (v != ver)
1212 luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
1213 (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
1214}
1215