lfunc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. ** $Id: lfunc.c,v 1.10 1999/03/04 21:17:26 roberto Exp roberto $
  3. ** Auxiliary functions to manipulate prototypes and closures
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #include "lfunc.h"
  8. #include "lmem.h"
  9. #include "lstate.h"
  10. #define gcsizeproto(p) 5 /* approximate "weight" for a prototype */
  11. #define gcsizeclosure(c) 1 /* approximate "weight" for a closure */
  12. Closure *luaF_newclosure (int nelems) {
  13. Closure *c = (Closure *)luaM_malloc(sizeof(Closure)+nelems*sizeof(TObject));
  14. luaO_insertlist(&(L->rootcl), (GCnode *)c);
  15. L->nblocks += gcsizeclosure(c);
  16. c->nelems = nelems;
  17. return c;
  18. }
  19. TProtoFunc *luaF_newproto (void) {
  20. TProtoFunc *f = luaM_new(TProtoFunc);
  21. f->code = NULL;
  22. f->lineDefined = 0;
  23. f->source = NULL;
  24. f->consts = NULL;
  25. f->nconsts = 0;
  26. f->locvars = NULL;
  27. luaO_insertlist(&(L->rootproto), (GCnode *)f);
  28. L->nblocks += gcsizeproto(f);
  29. return f;
  30. }
  31. static void freefunc (TProtoFunc *f) {
  32. luaM_free(f->code);
  33. luaM_free(f->locvars);
  34. luaM_free(f->consts);
  35. luaM_free(f);
  36. }
  37. void luaF_freeproto (TProtoFunc *l) {
  38. while (l) {
  39. TProtoFunc *next = (TProtoFunc *)l->head.next;
  40. L->nblocks -= gcsizeproto(l);
  41. freefunc(l);
  42. l = next;
  43. }
  44. }
  45. void luaF_freeclosure (Closure *l) {
  46. while (l) {
  47. Closure *next = (Closure *)l->head.next;
  48. L->nblocks -= gcsizeclosure(l);
  49. luaM_free(l);
  50. l = next;
  51. }
  52. }
  53. /*
  54. ** Look for n-th local variable at line "line" in function "func".
  55. ** Returns NULL if not found.
  56. */
  57. const char *luaF_getlocalname (TProtoFunc *func, int local_number, int line) {
  58. int count = 0;
  59. const char *varname = NULL;
  60. LocVar *lv = func->locvars;
  61. if (lv == NULL)
  62. return NULL;
  63. for (; lv->line != -1 && lv->line < line; lv++) {
  64. if (lv->varname) { /* register */
  65. if (++count == local_number)
  66. varname = lv->varname->str;
  67. }
  68. else /* unregister */
  69. if (--count < local_number)
  70. varname = NULL;
  71. }
  72. return varname;
  73. }