lfunc.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. ** $Id: lfunc.c,v 1.28 2000/08/08 20:42:07 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 "lua.h"
  8. #include "lfunc.h"
  9. #include "lmem.h"
  10. #include "lstate.h"
  11. #define gcsizeproto(L, p) numblocks(L, 0, sizeof(Proto))
  12. #define gcsizeclosure(L, c) numblocks(L, c->nupvalues, sizeof(Closure))
  13. Closure *luaF_newclosure (lua_State *L, int nelems) {
  14. Closure *c = (Closure *)luaM_malloc(L, sizeof(Closure) +
  15. (lint32)sizeof(TObject)*(nelems-1));
  16. c->next = L->rootcl;
  17. L->rootcl = c;
  18. c->mark = c;
  19. c->nupvalues = nelems;
  20. L->nblocks += gcsizeclosure(L, c);
  21. return c;
  22. }
  23. Proto *luaF_newproto (lua_State *L) {
  24. Proto *f = luaM_new(L, Proto);
  25. f->code = NULL;
  26. f->lineinfo = NULL;
  27. f->lineDefined = 0;
  28. f->source = NULL;
  29. f->kstr = NULL;
  30. f->nkstr = 0;
  31. f->knum = NULL;
  32. f->nknum = 0;
  33. f->kproto = NULL;
  34. f->nkproto = 0;
  35. f->locvars = NULL;
  36. f->next = L->rootproto;
  37. L->rootproto = f;
  38. f->marked = 0;
  39. L->nblocks += gcsizeproto(L, f);
  40. return f;
  41. }
  42. void luaF_freeproto (lua_State *L, Proto *f) {
  43. L->nblocks -= gcsizeproto(L, f);
  44. luaM_free(L, f->code);
  45. luaM_free(L, f->locvars);
  46. luaM_free(L, f->kstr);
  47. luaM_free(L, f->knum);
  48. luaM_free(L, f->kproto);
  49. luaM_free(L, f->lineinfo);
  50. luaM_free(L, f);
  51. }
  52. void luaF_freeclosure (lua_State *L, Closure *c) {
  53. L->nblocks -= gcsizeclosure(L, c);
  54. luaM_free(L, c);
  55. }
  56. /*
  57. ** Look for n-th local variable at line `line' in function `func'.
  58. ** Returns NULL if not found.
  59. */
  60. const char *luaF_getlocalname (const Proto *func, int local_number, int pc) {
  61. int count = 0;
  62. const char *varname = NULL;
  63. LocVar *lv = func->locvars;
  64. for (; lv->pc != -1 && lv->pc <= pc; 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. }