lfunc.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. ** $Id: lfunc.c,v 1.12 1999/10/04 17:51:04 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. c->next = L->rootcl;
  15. L->rootcl = c;
  16. c->marked = 0;
  17. L->nblocks += gcsizeclosure(c);
  18. c->nelems = nelems;
  19. return c;
  20. }
  21. TProtoFunc *luaF_newproto (void) {
  22. TProtoFunc *f = luaM_new(TProtoFunc);
  23. f->code = NULL;
  24. f->lineDefined = 0;
  25. f->source = NULL;
  26. f->consts = NULL;
  27. f->nconsts = 0;
  28. f->locvars = NULL;
  29. f->next = L->rootproto;
  30. L->rootproto = f;
  31. f->marked = 0;
  32. L->nblocks += gcsizeproto(f);
  33. return f;
  34. }
  35. void luaF_freeproto (TProtoFunc *f) {
  36. L->nblocks -= gcsizeproto(f);
  37. luaM_free(f->code);
  38. luaM_free(f->locvars);
  39. luaM_free(f->consts);
  40. luaM_free(f);
  41. }
  42. void luaF_freeclosure (Closure *c) {
  43. L->nblocks -= gcsizeclosure(c);
  44. luaM_free(c);
  45. }
  46. /*
  47. ** Look for n-th local variable at line "line" in function "func".
  48. ** Returns NULL if not found.
  49. */
  50. const char *luaF_getlocalname (const TProtoFunc *func,
  51. int local_number, int line) {
  52. int count = 0;
  53. const char *varname = NULL;
  54. LocVar *lv = func->locvars;
  55. if (lv == NULL)
  56. return NULL;
  57. for (; lv->line != -1 && lv->line < line; lv++) {
  58. if (lv->varname) { /* register */
  59. if (++count == local_number)
  60. varname = lv->varname->str;
  61. }
  62. else /* unregister */
  63. if (--count < local_number)
  64. varname = NULL;
  65. }
  66. return varname;
  67. }