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