lfunc.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. ** $Id: lfunc.c,v 1.18 2000/01/28 16:53:00 roberto Exp roberto $
  3. ** Auxiliary functions to manipulate prototypes and closures
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #define LUA_REENTRANT
  8. #include "lfunc.h"
  9. #include "lmem.h"
  10. #include "lstate.h"
  11. #define gcsizeproto(L, p) numblocks(L, 0, sizeof(TProtoFunc))
  12. #define gcsizeclosure(L, c) numblocks(L, c->nelems, sizeof(Closure))
  13. Closure *luaF_newclosure (lua_State *L, int nelems) {
  14. Closure *c = (Closure *)luaM_malloc(L, sizeof(Closure)+nelems*sizeof(TObject));
  15. c->next = L->rootcl;
  16. L->rootcl = c;
  17. c->marked = 0;
  18. c->nelems = nelems;
  19. L->nblocks += gcsizeclosure(L, c);
  20. return c;
  21. }
  22. TProtoFunc *luaF_newproto (lua_State *L) {
  23. TProtoFunc *f = luaM_new(L, TProtoFunc);
  24. f->code = NULL;
  25. f->lineDefined = 0;
  26. f->source = NULL;
  27. f->kstr = NULL;
  28. f->nkstr = 0;
  29. f->knum = NULL;
  30. f->nknum = 0;
  31. f->kproto = NULL;
  32. f->nkproto = 0;
  33. f->locvars = NULL;
  34. f->next = L->rootproto;
  35. L->rootproto = f;
  36. f->marked = 0;
  37. L->nblocks += gcsizeproto(L, f);
  38. return f;
  39. }
  40. void luaF_freeproto (lua_State *L, TProtoFunc *f) {
  41. L->nblocks -= gcsizeproto(L, f);
  42. luaM_free(L, f->code);
  43. luaM_free(L, f->locvars);
  44. luaM_free(L, f->kstr);
  45. luaM_free(L, f->knum);
  46. luaM_free(L, f->kproto);
  47. luaM_free(L, f);
  48. }
  49. void luaF_freeclosure (lua_State *L, Closure *c) {
  50. L->nblocks -= gcsizeclosure(L, c);
  51. luaM_free(L, c);
  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 (const TProtoFunc *func,
  58. int local_number, int line) {
  59. int count = 0;
  60. const char *varname = NULL;
  61. LocVar *lv = func->locvars;
  62. if (lv == NULL)
  63. return NULL;
  64. for (; lv->line != -1 && lv->line < line; lv++) {
  65. if (lv->varname) { /* register */
  66. if (++count == local_number)
  67. varname = lv->varname->str;
  68. }
  69. else /* unregister */
  70. if (--count < local_number)
  71. varname = NULL;
  72. }
  73. return varname;
  74. }