xref: /netbsd-src/external/mit/lua/dist/src/lapi.c (revision 53d1339bf7f9c7367b35a9e1ebe693f9b047a47b)
1 /*	$NetBSD: lapi.c,v 1.12 2019/12/12 12:35:43 mbalmer Exp $	*/
2 
3 /*
4 ** Id: lapi.c,v 2.259.1.2 2017/12/06 18:35:12 roberto Exp
5 ** Lua API
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lapi_c
10 #define LUA_CORE
11 
12 #include "lprefix.h"
13 
14 
15 #include <stdarg.h>
16 #ifndef _KERNEL
17 #include <string.h>
18 #endif /* _KERNEL */
19 
20 #include "lua.h"
21 
22 #include "lapi.h"
23 #include "ldebug.h"
24 #include "ldo.h"
25 #include "lfunc.h"
26 #include "lgc.h"
27 #include "lmem.h"
28 #include "lobject.h"
29 #include "lstate.h"
30 #include "lstring.h"
31 #include "ltable.h"
32 #include "ltm.h"
33 #include "lundump.h"
34 #include "lvm.h"
35 
36 
37 
38 const char lua_ident[] =
39   "$LuaVersion: " LUA_COPYRIGHT " $"
40   "$LuaAuthors: " LUA_AUTHORS " $";
41 
42 
43 /* value at a non-valid index */
44 #define NONVALIDVALUE		cast(TValue *, luaO_nilobject)
45 
46 /* corresponding test */
47 #define isvalid(o)	((o) != luaO_nilobject)
48 
49 /* test for pseudo index */
50 #define ispseudo(i)		((i) <= LUA_REGISTRYINDEX)
51 
52 /* test for upvalue */
53 #define isupvalue(i)		((i) < LUA_REGISTRYINDEX)
54 
55 /* test for valid but not pseudo index */
56 #define isstackindex(i, o)	(isvalid(o) && !ispseudo(i))
57 
58 #define api_checkvalidindex(l,o)  api_check(l, isvalid(o), "invalid index")
59 
60 #define api_checkstackindex(l, i, o)  \
61 	api_check(l, isstackindex(i, o), "index not in the stack")
62 
63 
64 static TValue *index2addr (lua_State *L, int idx) {
65   CallInfo *ci = L->ci;
66   if (idx > 0) {
67     TValue *o = ci->func + idx;
68     api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index");
69     if (o >= L->top) return NONVALIDVALUE;
70     else return o;
71   }
72   else if (!ispseudo(idx)) {  /* negative index */
73     api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
74     return L->top + idx;
75   }
76   else if (idx == LUA_REGISTRYINDEX)
77     return &G(L)->l_registry;
78   else {  /* upvalues */
79     idx = LUA_REGISTRYINDEX - idx;
80     api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
81     if (ttislcf(ci->func))  /* light C function? */
82       return NONVALIDVALUE;  /* it has no upvalues */
83     else {
84       CClosure *func = clCvalue(ci->func);
85       return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE;
86     }
87   }
88 }
89 
90 
91 /*
92 ** to be called by 'lua_checkstack' in protected mode, to grow stack
93 ** capturing memory errors
94 */
95 static void growstack (lua_State *L, void *ud) {
96   int size = *(int *)ud;
97   luaD_growstack(L, size);
98 }
99 
100 
101 LUA_API int lua_checkstack (lua_State *L, int n) {
102   int res;
103   CallInfo *ci = L->ci;
104   lua_lock(L);
105   api_check(L, n >= 0, "negative 'n'");
106   if (L->stack_last - L->top > n)  /* stack large enough? */
107     res = 1;  /* yes; check is OK */
108   else {  /* no; need to grow stack */
109     int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;
110     if (inuse > LUAI_MAXSTACK - n)  /* can grow without overflow? */
111       res = 0;  /* no */
112     else  /* try to grow stack */
113       res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK);
114   }
115   if (res && ci->top < L->top + n)
116     ci->top = L->top + n;  /* adjust frame top */
117   lua_unlock(L);
118   return res;
119 }
120 
121 
122 LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
123   int i;
124   if (from == to) return;
125   lua_lock(to);
126   api_checknelems(from, n);
127   api_check(from, G(from) == G(to), "moving among independent states");
128   api_check(from, to->ci->top - to->top >= n, "stack overflow");
129   from->top -= n;
130   for (i = 0; i < n; i++) {
131     setobj2s(to, to->top, from->top + i);
132     to->top++;  /* stack already checked by previous 'api_check' */
133   }
134   lua_unlock(to);
135 }
136 
137 
138 LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
139   lua_CFunction old;
140   lua_lock(L);
141   old = G(L)->panic;
142   G(L)->panic = panicf;
143   lua_unlock(L);
144   return old;
145 }
146 
147 
148 LUA_API const lua_Number *lua_version (lua_State *L) {
149   static const lua_Number version = LUA_VERSION_NUM;
150   if (L == NULL) return &version;
151   else return G(L)->version;
152 }
153 
154 
155 
156 /*
157 ** basic stack manipulation
158 */
159 
160 
161 /*
162 ** convert an acceptable stack index into an absolute index
163 */
164 LUA_API int lua_absindex (lua_State *L, int idx) {
165   return (idx > 0 || ispseudo(idx))
166          ? idx
167          : cast_int(L->top - L->ci->func) + idx;
168 }
169 
170 
171 LUA_API int lua_gettop (lua_State *L) {
172   return cast_int(L->top - (L->ci->func + 1));
173 }
174 
175 
176 LUA_API void lua_settop (lua_State *L, int idx) {
177   StkId func = L->ci->func;
178   lua_lock(L);
179   if (idx >= 0) {
180     api_check(L, idx <= L->stack_last - (func + 1), "new top too large");
181     while (L->top < (func + 1) + idx)
182       setnilvalue(L->top++);
183     L->top = (func + 1) + idx;
184   }
185   else {
186     api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");
187     L->top += idx+1;  /* 'subtract' index (index is negative) */
188   }
189   lua_unlock(L);
190 }
191 
192 
193 /*
194 ** Reverse the stack segment from 'from' to 'to'
195 ** (auxiliary to 'lua_rotate')
196 */
197 static void reverse (lua_State *L, StkId from, StkId to) {
198   for (; from < to; from++, to--) {
199     TValue temp;
200     setobj(L, &temp, from);
201     setobjs2s(L, from, to);
202     setobj2s(L, to, &temp);
203   }
204 }
205 
206 
207 /*
208 ** Let x = AB, where A is a prefix of length 'n'. Then,
209 ** rotate x n == BA. But BA == (A^r . B^r)^r.
210 */
211 LUA_API void lua_rotate (lua_State *L, int idx, int n) {
212   StkId p, t, m;
213   lua_lock(L);
214   t = L->top - 1;  /* end of stack segment being rotated */
215   p = index2addr(L, idx);  /* start of segment */
216   api_checkstackindex(L, idx, p);
217   api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
218   m = (n >= 0 ? t - n : p - n - 1);  /* end of prefix */
219   reverse(L, p, m);  /* reverse the prefix with length 'n' */
220   reverse(L, m + 1, t);  /* reverse the suffix */
221   reverse(L, p, t);  /* reverse the entire segment */
222   lua_unlock(L);
223 }
224 
225 
226 LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
227   TValue *fr, *to;
228   lua_lock(L);
229   fr = index2addr(L, fromidx);
230   to = index2addr(L, toidx);
231   api_checkvalidindex(L, to);
232   setobj(L, to, fr);
233   if (isupvalue(toidx))  /* function upvalue? */
234     luaC_barrier(L, clCvalue(L->ci->func), fr);
235   /* LUA_REGISTRYINDEX does not need gc barrier
236      (collector revisits it before finishing collection) */
237   lua_unlock(L);
238 }
239 
240 
241 LUA_API void lua_pushvalue (lua_State *L, int idx) {
242   lua_lock(L);
243   setobj2s(L, L->top, index2addr(L, idx));
244   api_incr_top(L);
245   lua_unlock(L);
246 }
247 
248 
249 
250 /*
251 ** access functions (stack -> C)
252 */
253 
254 
255 LUA_API int lua_type (lua_State *L, int idx) {
256   StkId o = index2addr(L, idx);
257   return (isvalid(o) ? ttnov(o) : LUA_TNONE);
258 }
259 
260 
261 LUA_API const char *lua_typename (lua_State *L, int t) {
262   UNUSED(L);
263   api_check(L, LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag");
264   return ttypename(t);
265 }
266 
267 
268 LUA_API int lua_iscfunction (lua_State *L, int idx) {
269   StkId o = index2addr(L, idx);
270   return (ttislcf(o) || (ttisCclosure(o)));
271 }
272 
273 
274 LUA_API int lua_isinteger (lua_State *L, int idx) {
275   StkId o = index2addr(L, idx);
276   return ttisinteger(o);
277 }
278 
279 
280 LUA_API int lua_isnumber (lua_State *L, int idx) {
281   lua_Number n;
282   const TValue *o = index2addr(L, idx);
283   return tonumber(o, &n);
284 }
285 
286 
287 LUA_API int lua_isstring (lua_State *L, int idx) {
288   const TValue *o = index2addr(L, idx);
289   return (ttisstring(o) || cvt2str(o));
290 }
291 
292 
293 LUA_API int lua_isuserdata (lua_State *L, int idx) {
294   const TValue *o = index2addr(L, idx);
295   return (ttisfulluserdata(o) || ttislightuserdata(o));
296 }
297 
298 
299 LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
300   StkId o1 = index2addr(L, index1);
301   StkId o2 = index2addr(L, index2);
302   return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0;
303 }
304 
305 
306 LUA_API void lua_arith (lua_State *L, int op) {
307   lua_lock(L);
308   if (op != LUA_OPUNM && op != LUA_OPBNOT)
309     api_checknelems(L, 2);  /* all other operations expect two operands */
310   else {  /* for unary operations, add fake 2nd operand */
311     api_checknelems(L, 1);
312     setobjs2s(L, L->top, L->top - 1);
313     api_incr_top(L);
314   }
315   /* first operand at top - 2, second at top - 1; result go to top - 2 */
316   luaO_arith(L, op, L->top - 2, L->top - 1, L->top - 2);
317   L->top--;  /* remove second operand */
318   lua_unlock(L);
319 }
320 
321 
322 LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
323   StkId o1, o2;
324   int i = 0;
325   lua_lock(L);  /* may call tag method */
326   o1 = index2addr(L, index1);
327   o2 = index2addr(L, index2);
328   if (isvalid(o1) && isvalid(o2)) {
329     switch (op) {
330       case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
331       case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
332       case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
333       default: api_check(L, 0, "invalid option");
334     }
335   }
336   lua_unlock(L);
337   return i;
338 }
339 
340 
341 LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
342   size_t sz = luaO_str2num(s, L->top);
343   if (sz != 0)
344     api_incr_top(L);
345   return sz;
346 }
347 
348 
349 #ifndef _KERNEL
350 LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
351   lua_Number n;
352   const TValue *o = index2addr(L, idx);
353   int isnum = tonumber(o, &n);
354   if (!isnum)
355     n = 0;  /* call to 'tonumber' may change 'n' even if it fails */
356   if (pisnum) *pisnum = isnum;
357   return n;
358 }
359 #endif /* _KERNEL */
360 
361 
362 LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
363   lua_Integer res;
364   const TValue *o = index2addr(L, idx);
365   int isnum = tointeger(o, &res);
366   if (!isnum)
367     res = 0;  /* call to 'tointeger' may change 'n' even if it fails */
368   if (pisnum) *pisnum = isnum;
369   return res;
370 }
371 
372 
373 LUA_API int lua_toboolean (lua_State *L, int idx) {
374   const TValue *o = index2addr(L, idx);
375   return !l_isfalse(o);
376 }
377 
378 
379 LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
380   StkId o = index2addr(L, idx);
381   if (!ttisstring(o)) {
382     if (!cvt2str(o)) {  /* not convertible? */
383       if (len != NULL) *len = 0;
384       return NULL;
385     }
386     lua_lock(L);  /* 'luaO_tostring' may create a new string */
387     luaO_tostring(L, o);
388     luaC_checkGC(L);
389     o = index2addr(L, idx);  /* previous call may reallocate the stack */
390     lua_unlock(L);
391   }
392   if (len != NULL)
393     *len = vslen(o);
394   return svalue(o);
395 }
396 
397 
398 LUA_API size_t lua_rawlen (lua_State *L, int idx) {
399   StkId o = index2addr(L, idx);
400   switch (ttype(o)) {
401     case LUA_TSHRSTR: return tsvalue(o)->shrlen;
402     case LUA_TLNGSTR: return tsvalue(o)->u.lnglen;
403     case LUA_TUSERDATA: return uvalue(o)->len;
404     case LUA_TTABLE: return luaH_getn(hvalue(o));
405     default: return 0;
406   }
407 }
408 
409 
410 LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
411   StkId o = index2addr(L, idx);
412   if (ttislcf(o)) return fvalue(o);
413   else if (ttisCclosure(o))
414     return clCvalue(o)->f;
415   else return NULL;  /* not a C function */
416 }
417 
418 
419 LUA_API void *lua_touserdata (lua_State *L, int idx) {
420   StkId o = index2addr(L, idx);
421   switch (ttnov(o)) {
422     case LUA_TUSERDATA: return getudatamem(uvalue(o));
423     case LUA_TLIGHTUSERDATA: return pvalue(o);
424     default: return NULL;
425   }
426 }
427 
428 
429 LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
430   StkId o = index2addr(L, idx);
431   return (!ttisthread(o)) ? NULL : thvalue(o);
432 }
433 
434 
435 LUA_API const void *lua_topointer (lua_State *L, int idx) {
436   StkId o = index2addr(L, idx);
437   switch (ttype(o)) {
438     case LUA_TTABLE: return hvalue(o);
439     case LUA_TLCL: return clLvalue(o);
440     case LUA_TCCL: return clCvalue(o);
441     case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));
442     case LUA_TTHREAD: return thvalue(o);
443     case LUA_TUSERDATA: return getudatamem(uvalue(o));
444     case LUA_TLIGHTUSERDATA: return pvalue(o);
445     default: return NULL;
446   }
447 }
448 
449 
450 
451 /*
452 ** push functions (C -> stack)
453 */
454 
455 
456 LUA_API void lua_pushnil (lua_State *L) {
457   lua_lock(L);
458   setnilvalue(L->top);
459   api_incr_top(L);
460   lua_unlock(L);
461 }
462 
463 
464 #ifndef _KERNEL
465 LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
466   lua_lock(L);
467   setfltvalue(L->top, n);
468   api_incr_top(L);
469   lua_unlock(L);
470 }
471 #endif /* _KERNEL */
472 
473 
474 LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
475   lua_lock(L);
476   setivalue(L->top, n);
477   api_incr_top(L);
478   lua_unlock(L);
479 }
480 
481 
482 /*
483 ** Pushes on the stack a string with given length. Avoid using 's' when
484 ** 'len' == 0 (as 's' can be NULL in that case), due to later use of
485 ** 'memcmp' and 'memcpy'.
486 */
487 LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
488   TString *ts;
489   lua_lock(L);
490   ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len);
491   setsvalue2s(L, L->top, ts);
492   api_incr_top(L);
493   luaC_checkGC(L);
494   lua_unlock(L);
495   return getstr(ts);
496 }
497 
498 
499 LUA_API const char *lua_pushstring (lua_State *L, const char *s) {
500   lua_lock(L);
501   if (s == NULL)
502     setnilvalue(L->top);
503   else {
504     TString *ts;
505     ts = luaS_new(L, s);
506     setsvalue2s(L, L->top, ts);
507     s = getstr(ts);  /* internal copy's address */
508   }
509   api_incr_top(L);
510   luaC_checkGC(L);
511   lua_unlock(L);
512   return s;
513 }
514 
515 
516 LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
517                                       va_list argp) {
518   const char *ret;
519   lua_lock(L);
520   ret = luaO_pushvfstring(L, fmt, argp);
521   luaC_checkGC(L);
522   lua_unlock(L);
523   return ret;
524 }
525 
526 
527 LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
528   const char *ret;
529   va_list argp;
530   lua_lock(L);
531   va_start(argp, fmt);
532   ret = luaO_pushvfstring(L, fmt, argp);
533   va_end(argp);
534   luaC_checkGC(L);
535   lua_unlock(L);
536   return ret;
537 }
538 
539 
540 LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
541   lua_lock(L);
542   if (n == 0) {
543     setfvalue(L->top, fn);
544     api_incr_top(L);
545   }
546   else {
547     CClosure *cl;
548     api_checknelems(L, n);
549     api_check(L, n <= MAXUPVAL, "upvalue index too large");
550     cl = luaF_newCclosure(L, n);
551     cl->f = fn;
552     L->top -= n;
553     while (n--) {
554       setobj2n(L, &cl->upvalue[n], L->top + n);
555       /* does not need barrier because closure is white */
556     }
557     setclCvalue(L, L->top, cl);
558     api_incr_top(L);
559     luaC_checkGC(L);
560   }
561   lua_unlock(L);
562 }
563 
564 
565 LUA_API void lua_pushboolean (lua_State *L, int b) {
566   lua_lock(L);
567   setbvalue(L->top, (b != 0));  /* ensure that true is 1 */
568   api_incr_top(L);
569   lua_unlock(L);
570 }
571 
572 
573 LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
574   lua_lock(L);
575   setpvalue(L->top, p);
576   api_incr_top(L);
577   lua_unlock(L);
578 }
579 
580 
581 LUA_API int lua_pushthread (lua_State *L) {
582   lua_lock(L);
583   setthvalue(L, L->top, L);
584   api_incr_top(L);
585   lua_unlock(L);
586   return (G(L)->mainthread == L);
587 }
588 
589 
590 
591 /*
592 ** get functions (Lua -> stack)
593 */
594 
595 
596 static int auxgetstr (lua_State *L, const TValue *t, const char *k) {
597   const TValue *slot;
598   TString *str = luaS_new(L, k);
599   if (luaV_fastget(L, t, str, slot, luaH_getstr)) {
600     setobj2s(L, L->top, slot);
601     api_incr_top(L);
602   }
603   else {
604     setsvalue2s(L, L->top, str);
605     api_incr_top(L);
606     luaV_finishget(L, t, L->top - 1, L->top - 1, slot);
607   }
608   lua_unlock(L);
609   return ttnov(L->top - 1);
610 }
611 
612 
613 LUA_API int lua_getglobal (lua_State *L, const char *name) {
614   Table *reg = hvalue(&G(L)->l_registry);
615   lua_lock(L);
616   return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);
617 }
618 
619 
620 LUA_API int lua_gettable (lua_State *L, int idx) {
621   StkId t;
622   lua_lock(L);
623   t = index2addr(L, idx);
624   luaV_gettable(L, t, L->top - 1, L->top - 1);
625   lua_unlock(L);
626   return ttnov(L->top - 1);
627 }
628 
629 
630 LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
631   lua_lock(L);
632   return auxgetstr(L, index2addr(L, idx), k);
633 }
634 
635 
636 LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
637   StkId t;
638   const TValue *slot;
639   lua_lock(L);
640   t = index2addr(L, idx);
641   if (luaV_fastget(L, t, n, slot, luaH_getint)) {
642     setobj2s(L, L->top, slot);
643     api_incr_top(L);
644   }
645   else {
646     setivalue(L->top, n);
647     api_incr_top(L);
648     luaV_finishget(L, t, L->top - 1, L->top - 1, slot);
649   }
650   lua_unlock(L);
651   return ttnov(L->top - 1);
652 }
653 
654 
655 LUA_API int lua_rawget (lua_State *L, int idx) {
656   StkId t;
657   lua_lock(L);
658   t = index2addr(L, idx);
659   api_check(L, ttistable(t), "table expected");
660   setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
661   lua_unlock(L);
662   return ttnov(L->top - 1);
663 }
664 
665 
666 LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
667   StkId t;
668   lua_lock(L);
669   t = index2addr(L, idx);
670   api_check(L, ttistable(t), "table expected");
671   setobj2s(L, L->top, luaH_getint(hvalue(t), n));
672   api_incr_top(L);
673   lua_unlock(L);
674   return ttnov(L->top - 1);
675 }
676 
677 
678 LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
679   StkId t;
680   TValue k;
681   lua_lock(L);
682   t = index2addr(L, idx);
683   api_check(L, ttistable(t), "table expected");
684   setpvalue(&k, cast(void *, p));
685   setobj2s(L, L->top, luaH_get(hvalue(t), &k));
686   api_incr_top(L);
687   lua_unlock(L);
688   return ttnov(L->top - 1);
689 }
690 
691 
692 LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
693   Table *t;
694   lua_lock(L);
695   t = luaH_new(L);
696   sethvalue(L, L->top, t);
697   api_incr_top(L);
698   if (narray > 0 || nrec > 0)
699     luaH_resize(L, t, narray, nrec);
700   luaC_checkGC(L);
701   lua_unlock(L);
702 }
703 
704 
705 LUA_API int lua_getmetatable (lua_State *L, int objindex) {
706   const TValue *obj;
707   Table *mt;
708   int res = 0;
709   lua_lock(L);
710   obj = index2addr(L, objindex);
711   switch (ttnov(obj)) {
712     case LUA_TTABLE:
713       mt = hvalue(obj)->metatable;
714       break;
715     case LUA_TUSERDATA:
716       mt = uvalue(obj)->metatable;
717       break;
718     default:
719       mt = G(L)->mt[ttnov(obj)];
720       break;
721   }
722   if (mt != NULL) {
723     sethvalue(L, L->top, mt);
724     api_incr_top(L);
725     res = 1;
726   }
727   lua_unlock(L);
728   return res;
729 }
730 
731 
732 LUA_API int lua_getuservalue (lua_State *L, int idx) {
733   StkId o;
734   lua_lock(L);
735   o = index2addr(L, idx);
736   api_check(L, ttisfulluserdata(o), "full userdata expected");
737   getuservalue(L, uvalue(o), L->top);
738   api_incr_top(L);
739   lua_unlock(L);
740   return ttnov(L->top - 1);
741 }
742 
743 
744 /*
745 ** set functions (stack -> Lua)
746 */
747 
748 /*
749 ** t[k] = value at the top of the stack (where 'k' is a string)
750 */
751 static void auxsetstr (lua_State *L, const TValue *t, const char *k) {
752   const TValue *slot;
753   TString *str = luaS_new(L, k);
754   api_checknelems(L, 1);
755   if (luaV_fastset(L, t, str, slot, luaH_getstr, L->top - 1))
756     L->top--;  /* pop value */
757   else {
758     setsvalue2s(L, L->top, str);  /* push 'str' (to make it a TValue) */
759     api_incr_top(L);
760     luaV_finishset(L, t, L->top - 1, L->top - 2, slot);
761     L->top -= 2;  /* pop value and key */
762   }
763   lua_unlock(L);  /* lock done by caller */
764 }
765 
766 
767 LUA_API void lua_setglobal (lua_State *L, const char *name) {
768   Table *reg = hvalue(&G(L)->l_registry);
769   lua_lock(L);  /* unlock done in 'auxsetstr' */
770   auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);
771 }
772 
773 
774 LUA_API void lua_settable (lua_State *L, int idx) {
775   StkId t;
776   lua_lock(L);
777   api_checknelems(L, 2);
778   t = index2addr(L, idx);
779   luaV_settable(L, t, L->top - 2, L->top - 1);
780   L->top -= 2;  /* pop index and value */
781   lua_unlock(L);
782 }
783 
784 
785 LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
786   lua_lock(L);  /* unlock done in 'auxsetstr' */
787   auxsetstr(L, index2addr(L, idx), k);
788 }
789 
790 
791 LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
792   StkId t;
793   const TValue *slot;
794   lua_lock(L);
795   api_checknelems(L, 1);
796   t = index2addr(L, idx);
797   if (luaV_fastset(L, t, n, slot, luaH_getint, L->top - 1))
798     L->top--;  /* pop value */
799   else {
800     setivalue(L->top, n);
801     api_incr_top(L);
802     luaV_finishset(L, t, L->top - 1, L->top - 2, slot);
803     L->top -= 2;  /* pop value and key */
804   }
805   lua_unlock(L);
806 }
807 
808 
809 LUA_API void lua_rawset (lua_State *L, int idx) {
810   StkId o;
811   TValue *slot;
812   lua_lock(L);
813   api_checknelems(L, 2);
814   o = index2addr(L, idx);
815   api_check(L, ttistable(o), "table expected");
816   slot = luaH_set(L, hvalue(o), L->top - 2);
817   setobj2t(L, slot, L->top - 1);
818   invalidateTMcache(hvalue(o));
819   luaC_barrierback(L, hvalue(o), L->top-1);
820   L->top -= 2;
821   lua_unlock(L);
822 }
823 
824 
825 LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
826   StkId o;
827   lua_lock(L);
828   api_checknelems(L, 1);
829   o = index2addr(L, idx);
830   api_check(L, ttistable(o), "table expected");
831   luaH_setint(L, hvalue(o), n, L->top - 1);
832   luaC_barrierback(L, hvalue(o), L->top-1);
833   L->top--;
834   lua_unlock(L);
835 }
836 
837 
838 LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
839   StkId o;
840   TValue k, *slot;
841   lua_lock(L);
842   api_checknelems(L, 1);
843   o = index2addr(L, idx);
844   api_check(L, ttistable(o), "table expected");
845   setpvalue(&k, cast(void *, p));
846   slot = luaH_set(L, hvalue(o), &k);
847   setobj2t(L, slot, L->top - 1);
848   luaC_barrierback(L, hvalue(o), L->top - 1);
849   L->top--;
850   lua_unlock(L);
851 }
852 
853 
854 LUA_API int lua_setmetatable (lua_State *L, int objindex) {
855   TValue *obj;
856   Table *mt;
857   lua_lock(L);
858   api_checknelems(L, 1);
859   obj = index2addr(L, objindex);
860   if (ttisnil(L->top - 1))
861     mt = NULL;
862   else {
863     api_check(L, ttistable(L->top - 1), "table expected");
864     mt = hvalue(L->top - 1);
865   }
866   switch (ttnov(obj)) {
867     case LUA_TTABLE: {
868       hvalue(obj)->metatable = mt;
869       if (mt) {
870         luaC_objbarrier(L, gcvalue(obj), mt);
871         luaC_checkfinalizer(L, gcvalue(obj), mt);
872       }
873       break;
874     }
875     case LUA_TUSERDATA: {
876       uvalue(obj)->metatable = mt;
877       if (mt) {
878         luaC_objbarrier(L, uvalue(obj), mt);
879         luaC_checkfinalizer(L, gcvalue(obj), mt);
880       }
881       break;
882     }
883     default: {
884       G(L)->mt[ttnov(obj)] = mt;
885       break;
886     }
887   }
888   L->top--;
889   lua_unlock(L);
890   return 1;
891 }
892 
893 
894 LUA_API void lua_setuservalue (lua_State *L, int idx) {
895   StkId o;
896   lua_lock(L);
897   api_checknelems(L, 1);
898   o = index2addr(L, idx);
899   api_check(L, ttisfulluserdata(o), "full userdata expected");
900   setuservalue(L, uvalue(o), L->top - 1);
901   luaC_barrier(L, gcvalue(o), L->top - 1);
902   L->top--;
903   lua_unlock(L);
904 }
905 
906 
907 /*
908 ** 'load' and 'call' functions (run Lua code)
909 */
910 
911 
912 #define checkresults(L,na,nr) \
913      api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
914 	"results from function overflow current stack size")
915 
916 
917 LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
918                         lua_KContext ctx, lua_KFunction k) {
919   StkId func;
920   lua_lock(L);
921   api_check(L, k == NULL || !isLua(L->ci),
922     "cannot use continuations inside hooks");
923   api_checknelems(L, nargs+1);
924   api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
925   checkresults(L, nargs, nresults);
926   func = L->top - (nargs+1);
927   if (k != NULL && L->nny == 0) {  /* need to prepare continuation? */
928     L->ci->u.c.k = k;  /* save continuation */
929     L->ci->u.c.ctx = ctx;  /* save context */
930     luaD_call(L, func, nresults);  /* do the call */
931   }
932   else  /* no continuation or no yieldable */
933     luaD_callnoyield(L, func, nresults);  /* just do the call */
934   adjustresults(L, nresults);
935   lua_unlock(L);
936 }
937 
938 
939 
940 /*
941 ** Execute a protected call.
942 */
943 struct CallS {  /* data to 'f_call' */
944   StkId func;
945   int nresults;
946 };
947 
948 
949 static void f_call (lua_State *L, void *ud) {
950   struct CallS *c = cast(struct CallS *, ud);
951   luaD_callnoyield(L, c->func, c->nresults);
952 }
953 
954 
955 
956 LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
957                         lua_KContext ctx, lua_KFunction k) {
958   struct CallS c;
959   int status;
960   ptrdiff_t func;
961   lua_lock(L);
962   api_check(L, k == NULL || !isLua(L->ci),
963     "cannot use continuations inside hooks");
964   api_checknelems(L, nargs+1);
965   api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
966   checkresults(L, nargs, nresults);
967   if (errfunc == 0)
968     func = 0;
969   else {
970     StkId o = index2addr(L, errfunc);
971     api_checkstackindex(L, errfunc, o);
972     func = savestack(L, o);
973   }
974   c.func = L->top - (nargs+1);  /* function to be called */
975   if (k == NULL || L->nny > 0) {  /* no continuation or no yieldable? */
976     c.nresults = nresults;  /* do a 'conventional' protected call */
977     status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
978   }
979   else {  /* prepare continuation (call is already protected by 'resume') */
980     CallInfo *ci = L->ci;
981     ci->u.c.k = k;  /* save continuation */
982     ci->u.c.ctx = ctx;  /* save context */
983     /* save information for error recovery */
984     ci->extra = savestack(L, c.func);
985     ci->u.c.old_errfunc = L->errfunc;
986     L->errfunc = func;
987     setoah(ci->callstatus, L->allowhook);  /* save value of 'allowhook' */
988     ci->callstatus |= CIST_YPCALL;  /* function can do error recovery */
989     luaD_call(L, c.func, nresults);  /* do the call */
990     ci->callstatus &= ~CIST_YPCALL;
991     L->errfunc = ci->u.c.old_errfunc;
992     status = LUA_OK;  /* if it is here, there were no errors */
993   }
994   adjustresults(L, nresults);
995   lua_unlock(L);
996   return status;
997 }
998 
999 
1000 LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
1001                       const char *chunkname, const char *mode) {
1002   ZIO z;
1003   int status;
1004   lua_lock(L);
1005   if (!chunkname) chunkname = "?";
1006   luaZ_init(L, &z, reader, data);
1007   status = luaD_protectedparser(L, &z, chunkname, mode);
1008   if (status == LUA_OK) {  /* no errors? */
1009     LClosure *f = clLvalue(L->top - 1);  /* get newly created function */
1010     if (f->nupvalues >= 1) {  /* does it have an upvalue? */
1011       /* get global table from registry */
1012       Table *reg = hvalue(&G(L)->l_registry);
1013       const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
1014       /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
1015       setobj(L, f->upvals[0]->v, gt);
1016       luaC_upvalbarrier(L, f->upvals[0]);
1017     }
1018   }
1019   lua_unlock(L);
1020   return status;
1021 }
1022 
1023 
1024 LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
1025   int status;
1026   TValue *o;
1027   lua_lock(L);
1028   api_checknelems(L, 1);
1029   o = L->top - 1;
1030   if (isLfunction(o))
1031     status = luaU_dump(L, getproto(o), writer, data, strip);
1032   else
1033     status = 1;
1034   lua_unlock(L);
1035   return status;
1036 }
1037 
1038 
1039 LUA_API int lua_status (lua_State *L) {
1040   return L->status;
1041 }
1042 
1043 
1044 /*
1045 ** Garbage-collection function
1046 */
1047 
1048 LUA_API int lua_gc (lua_State *L, int what, int data) {
1049   int res = 0;
1050   global_State *g;
1051   lua_lock(L);
1052   g = G(L);
1053   switch (what) {
1054     case LUA_GCSTOP: {
1055       g->gcrunning = 0;
1056       break;
1057     }
1058     case LUA_GCRESTART: {
1059       luaE_setdebt(g, 0);
1060       g->gcrunning = 1;
1061       break;
1062     }
1063     case LUA_GCCOLLECT: {
1064       luaC_fullgc(L, 0);
1065       break;
1066     }
1067     case LUA_GCCOUNT: {
1068       /* GC values are expressed in Kbytes: #bytes/2^10 */
1069       res = cast_int(gettotalbytes(g) >> 10);
1070       break;
1071     }
1072     case LUA_GCCOUNTB: {
1073       res = cast_int(gettotalbytes(g) & 0x3ff);
1074       break;
1075     }
1076     case LUA_GCSTEP: {
1077       l_mem debt = 1;  /* =1 to signal that it did an actual step */
1078       lu_byte oldrunning = g->gcrunning;
1079       g->gcrunning = 1;  /* allow GC to run */
1080       if (data == 0) {
1081         luaE_setdebt(g, -GCSTEPSIZE);  /* to do a "small" step */
1082         luaC_step(L);
1083       }
1084       else {  /* add 'data' to total debt */
1085         debt = cast(l_mem, data) * 1024 + g->GCdebt;
1086         luaE_setdebt(g, debt);
1087         luaC_checkGC(L);
1088       }
1089       g->gcrunning = oldrunning;  /* restore previous state */
1090       if (debt > 0 && g->gcstate == GCSpause)  /* end of cycle? */
1091         res = 1;  /* signal it */
1092       break;
1093     }
1094     case LUA_GCSETPAUSE: {
1095       res = g->gcpause;
1096       g->gcpause = data;
1097       break;
1098     }
1099     case LUA_GCSETSTEPMUL: {
1100       res = g->gcstepmul;
1101       if (data < 40) data = 40;  /* avoid ridiculous low values (and 0) */
1102       g->gcstepmul = data;
1103       break;
1104     }
1105     case LUA_GCISRUNNING: {
1106       res = g->gcrunning;
1107       break;
1108     }
1109     default: res = -1;  /* invalid option */
1110   }
1111   lua_unlock(L);
1112   return res;
1113 }
1114 
1115 
1116 
1117 /*
1118 ** miscellaneous functions
1119 */
1120 
1121 
1122 LUA_API int lua_error (lua_State *L) {
1123   lua_lock(L);
1124   api_checknelems(L, 1);
1125   luaG_errormsg(L);
1126   /* code unreachable; will unlock when control actually leaves the kernel */
1127   return 0;  /* to avoid warnings */
1128 }
1129 
1130 
1131 LUA_API int lua_next (lua_State *L, int idx) {
1132   StkId t;
1133   int more;
1134   lua_lock(L);
1135   t = index2addr(L, idx);
1136   api_check(L, ttistable(t), "table expected");
1137   more = luaH_next(L, hvalue(t), L->top - 1);
1138   if (more) {
1139     api_incr_top(L);
1140   }
1141   else  /* no more elements */
1142     L->top -= 1;  /* remove key */
1143   lua_unlock(L);
1144   return more;
1145 }
1146 
1147 
1148 LUA_API void lua_concat (lua_State *L, int n) {
1149   lua_lock(L);
1150   api_checknelems(L, n);
1151   if (n >= 2) {
1152     luaV_concat(L, n);
1153   }
1154   else if (n == 0) {  /* push empty string */
1155     setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
1156     api_incr_top(L);
1157   }
1158   /* else n == 1; nothing to do */
1159   luaC_checkGC(L);
1160   lua_unlock(L);
1161 }
1162 
1163 
1164 LUA_API void lua_len (lua_State *L, int idx) {
1165   StkId t;
1166   lua_lock(L);
1167   t = index2addr(L, idx);
1168   luaV_objlen(L, L->top, t);
1169   api_incr_top(L);
1170   lua_unlock(L);
1171 }
1172 
1173 
1174 LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
1175   lua_Alloc f;
1176   lua_lock(L);
1177   if (ud) *ud = G(L)->ud;
1178   f = G(L)->frealloc;
1179   lua_unlock(L);
1180   return f;
1181 }
1182 
1183 
1184 LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
1185   lua_lock(L);
1186   G(L)->ud = ud;
1187   G(L)->frealloc = f;
1188   lua_unlock(L);
1189 }
1190 
1191 
1192 LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
1193   Udata *u;
1194   lua_lock(L);
1195   u = luaS_newudata(L, size);
1196   setuvalue(L, L->top, u);
1197   api_incr_top(L);
1198   luaC_checkGC(L);
1199   lua_unlock(L);
1200   return getudatamem(u);
1201 }
1202 
1203 
1204 
1205 static const char *aux_upvalue (StkId fi, int n, TValue **val,
1206                                 CClosure **owner, UpVal **uv) {
1207   switch (ttype(fi)) {
1208     case LUA_TCCL: {  /* C closure */
1209       CClosure *f = clCvalue(fi);
1210       if (!(1 <= n && n <= f->nupvalues)) return NULL;
1211       *val = &f->upvalue[n-1];
1212       if (owner) *owner = f;
1213       return "";
1214     }
1215     case LUA_TLCL: {  /* Lua closure */
1216       LClosure *f = clLvalue(fi);
1217       TString *name;
1218       Proto *p = f->p;
1219       if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
1220       *val = f->upvals[n-1]->v;
1221       if (uv) *uv = f->upvals[n - 1];
1222       name = p->upvalues[n-1].name;
1223       return (name == NULL) ? "(*no name)" : getstr(name);
1224     }
1225     default: return NULL;  /* not a closure */
1226   }
1227 }
1228 
1229 
1230 LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
1231   const char *name;
1232   TValue *val = NULL;  /* to avoid warnings */
1233   lua_lock(L);
1234   name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL);
1235   if (name) {
1236     setobj2s(L, L->top, val);
1237     api_incr_top(L);
1238   }
1239   lua_unlock(L);
1240   return name;
1241 }
1242 
1243 
1244 LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
1245   const char *name;
1246   TValue *val = NULL;  /* to avoid warnings */
1247   CClosure *owner = NULL;
1248   UpVal *uv = NULL;
1249   StkId fi;
1250   lua_lock(L);
1251   fi = index2addr(L, funcindex);
1252   api_checknelems(L, 1);
1253   name = aux_upvalue(fi, n, &val, &owner, &uv);
1254   if (name) {
1255     L->top--;
1256     setobj(L, val, L->top);
1257     if (owner) { luaC_barrier(L, owner, L->top); }
1258     else if (uv) { luaC_upvalbarrier(L, uv); }
1259   }
1260   lua_unlock(L);
1261   return name;
1262 }
1263 
1264 
1265 static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
1266   LClosure *f;
1267   StkId fi = index2addr(L, fidx);
1268   api_check(L, ttisLclosure(fi), "Lua function expected");
1269   f = clLvalue(fi);
1270   api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
1271   if (pf) *pf = f;
1272   return &f->upvals[n - 1];  /* get its upvalue pointer */
1273 }
1274 
1275 
1276 LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
1277   StkId fi = index2addr(L, fidx);
1278   switch (ttype(fi)) {
1279     case LUA_TLCL: {  /* lua closure */
1280       return *getupvalref(L, fidx, n, NULL);
1281     }
1282     case LUA_TCCL: {  /* C closure */
1283       CClosure *f = clCvalue(fi);
1284       api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
1285       return &f->upvalue[n - 1];
1286     }
1287     default: {
1288       api_check(L, 0, "closure expected");
1289       return NULL;
1290     }
1291   }
1292 }
1293 
1294 
1295 LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
1296                                             int fidx2, int n2) {
1297   LClosure *f1;
1298   UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
1299   UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
1300   if (*up1 == *up2)
1301     return;
1302   luaC_upvdeccount(L, *up1);
1303   *up1 = *up2;
1304   (*up1)->refcount++;
1305   if (upisopen(*up1)) (*up1)->u.open.touched = 1;
1306   luaC_upvalbarrier(L, *up1);
1307 }
1308 
1309 
1310