lstate.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. ** $Id: lstate.c,v 1.37 2000/09/11 17:38:42 roberto Exp roberto $
  3. ** Global State
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdarg.h>
  7. #include "lua.h"
  8. #include "ldo.h"
  9. #include "lgc.h"
  10. #include "llex.h"
  11. #include "lmem.h"
  12. #include "lstate.h"
  13. #include "lstring.h"
  14. #include "ltable.h"
  15. #include "ltm.h"
  16. #ifdef DEBUG
  17. extern lua_State *lua_state;
  18. void luaB_opentests (lua_State *L);
  19. #endif
  20. lua_State *lua_open (int stacksize) {
  21. struct lua_longjmp myErrorJmp;
  22. lua_State *L = luaM_new(NULL, lua_State);
  23. if (L == NULL) return NULL; /* memory allocation error */
  24. L->stack = NULL;
  25. L->strt.size = L->udt.size = 0;
  26. L->strt.nuse = L->udt.nuse = 0;
  27. L->strt.hash = NULL;
  28. L->udt.hash = NULL;
  29. L->Mbuffer = NULL;
  30. L->Mbuffsize = 0;
  31. L->rootproto = NULL;
  32. L->rootcl = NULL;
  33. L->roottable = NULL;
  34. L->IMtable = NULL;
  35. L->last_tag = -1;
  36. L->refArray = NULL;
  37. L->refSize = 0;
  38. L->refFree = NONEXT;
  39. L->nblocks = 0;
  40. L->GCthreshold = MAX_INT; /* to avoid GC during pre-definitions */
  41. L->callhook = NULL;
  42. L->linehook = NULL;
  43. L->allowhooks = 1;
  44. L->errorJmp = &myErrorJmp;
  45. if (setjmp(myErrorJmp.b) == 0) { /* to catch memory allocation errors */
  46. L->gt = luaH_new(L, 10);
  47. luaD_init(L, (stacksize == 0) ? DEFAULT_STACK_SIZE :
  48. stacksize+LUA_MINSTACK);
  49. luaS_init(L);
  50. luaX_init(L);
  51. luaT_init(L);
  52. #ifdef DEBUG
  53. luaB_opentests(L);
  54. #endif
  55. L->GCthreshold = L->nblocks*4;
  56. L->errorJmp = NULL;
  57. return L;
  58. }
  59. else { /* memory allocation error: free partial state */
  60. lua_close(L);
  61. return NULL;
  62. }
  63. }
  64. void lua_close (lua_State *L) {
  65. luaC_collect(L, 1); /* collect all elements */
  66. LUA_ASSERT(L->rootproto == NULL, "list should be empty");
  67. LUA_ASSERT(L->rootcl == NULL, "list should be empty");
  68. LUA_ASSERT(L->roottable == NULL, "list should be empty");
  69. luaS_freeall(L);
  70. luaM_free(L, L->stack);
  71. luaM_free(L, L->IMtable);
  72. luaM_free(L, L->refArray);
  73. luaM_free(L, L->Mbuffer);
  74. LUA_ASSERT(L->nblocks == 0, "wrong count for nblocks");
  75. luaM_free(L, L);
  76. LUA_ASSERT(L->Cbase == L->stack, "stack not empty");
  77. LUA_ASSERT(L != lua_state || memdebug_numblocks == 0, "memory leak!");
  78. LUA_ASSERT(L != lua_state || memdebug_total == 0,"memory leak!");
  79. }