Imported from ../lua-3.1.tar.gz.
[lua.git] / src / lfunc.c
blobfae59667ce2ab65d9dfbbecd9859a4b73137152c
1 /*
2 ** $Id: lfunc.c,v 1.9 1998/06/19 16:14:09 roberto Exp $
3 ** Auxiliary functions to manipulate prototypes and closures
4 ** See Copyright Notice in lua.h
5 */
8 #include <stdlib.h>
10 #include "lfunc.h"
11 #include "lmem.h"
12 #include "lstate.h"
14 #define gcsizeproto(p) 5 /* approximate "weight" for a prototype */
15 #define gcsizeclosure(c) 1 /* approximate "weight" for a closure */
19 Closure *luaF_newclosure (int nelems)
21 Closure *c = (Closure *)luaM_malloc(sizeof(Closure)+nelems*sizeof(TObject));
22 luaO_insertlist(&(L->rootcl), (GCnode *)c);
23 L->nblocks += gcsizeclosure(c);
24 c->nelems = nelems;
25 return c;
29 TProtoFunc *luaF_newproto (void)
31 TProtoFunc *f = luaM_new(TProtoFunc);
32 f->code = NULL;
33 f->lineDefined = 0;
34 f->fileName = NULL;
35 f->consts = NULL;
36 f->nconsts = 0;
37 f->locvars = NULL;
38 luaO_insertlist(&(L->rootproto), (GCnode *)f);
39 L->nblocks += gcsizeproto(f);
40 return f;
45 static void freefunc (TProtoFunc *f)
47 luaM_free(f->code);
48 luaM_free(f->locvars);
49 luaM_free(f->consts);
50 luaM_free(f);
54 void luaF_freeproto (TProtoFunc *l)
56 while (l) {
57 TProtoFunc *next = (TProtoFunc *)l->head.next;
58 L->nblocks -= gcsizeproto(l);
59 freefunc(l);
60 l = next;
65 void luaF_freeclosure (Closure *l)
67 while (l) {
68 Closure *next = (Closure *)l->head.next;
69 L->nblocks -= gcsizeclosure(l);
70 luaM_free(l);
71 l = next;
77 ** Look for n-th local variable at line "line" in function "func".
78 ** Returns NULL if not found.
80 char *luaF_getlocalname (TProtoFunc *func, int local_number, int line)
82 int count = 0;
83 char *varname = NULL;
84 LocVar *lv = func->locvars;
85 if (lv == NULL)
86 return NULL;
87 for (; lv->line != -1 && lv->line < line; lv++) {
88 if (lv->varname) { /* register */
89 if (++count == local_number)
90 varname = lv->varname->str;
92 else /* unregister */
93 if (--count < local_number)
94 varname = NULL;
96 return varname;