lfunc.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. ** $Id: lfunc.c,v 1.23 2000/05/30 19:00:31 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 "lua.h"
  9. #include "lfunc.h"
  10. #include "lmem.h"
  11. #include "lstate.h"
  12. #define gcsizeproto(L, p) numblocks(L, 0, sizeof(Proto))
  13. #define gcsizeclosure(L, c) numblocks(L, c->nupvalues, sizeof(Closure))
  14. Closure *luaF_newclosure (lua_State *L, int nelems) {
  15. Closure *c = (Closure *)luaM_malloc(L, sizeof(Closure) +
  16. (lint32)sizeof(TObject)*(nelems-1));
  17. c->next = L->rootcl;
  18. L->rootcl = c;
  19. c->marked = 0;
  20. c->nupvalues = nelems;
  21. L->nblocks += gcsizeclosure(L, c);
  22. return c;
  23. }
  24. Proto *luaF_newproto (lua_State *L) {
  25. Proto *f = luaM_new(L, Proto);
  26. f->code = 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);
  50. }
  51. void luaF_freeclosure (lua_State *L, Closure *c) {
  52. L->nblocks -= gcsizeclosure(L, c);
  53. luaM_free(L, c);
  54. }
  55. /*
  56. ** Look for n-th local variable at line `line' in function `func'.
  57. ** Returns NULL if not found.
  58. */
  59. const char *luaF_getlocalname (const Proto *func,
  60. int local_number, int line) {
  61. int count = 0;
  62. const char *varname = NULL;
  63. LocVar *lv = func->locvars;
  64. if (lv == NULL)
  65. return NULL;
  66. for (; lv->line != -1 && lv->line < line; lv++) {
  67. if (lv->varname) { /* register */
  68. if (++count == local_number)
  69. varname = lv->varname->str;
  70. }
  71. else /* unregister */
  72. if (--count < local_number)
  73. varname = NULL;
  74. }
  75. return varname;
  76. }