lfunc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. ** $Id: lfunc.c,v 1.8 1997/12/15 16:17:20 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. {
  14. Closure *c = (Closure *)luaM_malloc(sizeof(Closure)+nelems*sizeof(TObject));
  15. luaO_insertlist(&(L->rootcl), (GCnode *)c);
  16. L->nblocks += gcsizeclosure(c);
  17. c->nelems = nelems;
  18. return c;
  19. }
  20. TProtoFunc *luaF_newproto (void)
  21. {
  22. TProtoFunc *f = luaM_new(TProtoFunc);
  23. f->code = NULL;
  24. f->lineDefined = 0;
  25. f->fileName = NULL;
  26. f->consts = NULL;
  27. f->nconsts = 0;
  28. f->locvars = NULL;
  29. luaO_insertlist(&(L->rootproto), (GCnode *)f);
  30. L->nblocks += gcsizeproto(f);
  31. return f;
  32. }
  33. static void freefunc (TProtoFunc *f)
  34. {
  35. luaM_free(f->code);
  36. luaM_free(f->locvars);
  37. luaM_free(f->consts);
  38. luaM_free(f);
  39. }
  40. void luaF_freeproto (TProtoFunc *l)
  41. {
  42. while (l) {
  43. TProtoFunc *next = (TProtoFunc *)l->head.next;
  44. L->nblocks -= gcsizeproto(l);
  45. freefunc(l);
  46. l = next;
  47. }
  48. }
  49. void luaF_freeclosure (Closure *l)
  50. {
  51. while (l) {
  52. Closure *next = (Closure *)l->head.next;
  53. L->nblocks -= gcsizeclosure(l);
  54. luaM_free(l);
  55. l = next;
  56. }
  57. }
  58. /*
  59. ** Look for n-th local variable at line "line" in function "func".
  60. ** Returns NULL if not found.
  61. */
  62. char *luaF_getlocalname (TProtoFunc *func, int local_number, int line)
  63. {
  64. int count = 0;
  65. char *varname = NULL;
  66. LocVar *lv = func->locvars;
  67. if (lv == NULL)
  68. return NULL;
  69. for (; lv->line != -1 && lv->line < line; lv++) {
  70. if (lv->varname) { /* register */
  71. if (++count == local_number)
  72. varname = lv->varname->str;
  73. }
  74. else /* unregister */
  75. if (--count < local_number)
  76. varname = NULL;
  77. }
  78. return varname;
  79. }