lstate.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. ** $Id: lstate.c,v 1.35 2000/08/31 13:30:39 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_newstate (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->Mbuffbase = 0;
  31. L->Mbuffsize = 0;
  32. L->Mbuffnext = 0;
  33. L->rootproto = NULL;
  34. L->rootcl = NULL;
  35. L->roottable = NULL;
  36. L->IMtable = NULL;
  37. L->last_tag = -1;
  38. L->refArray = NULL;
  39. L->refSize = 0;
  40. L->refFree = NONEXT;
  41. L->nblocks = 0;
  42. L->GCthreshold = MAX_INT; /* to avoid GC during pre-definitions */
  43. L->callhook = NULL;
  44. L->linehook = NULL;
  45. L->allowhooks = 1;
  46. L->errorJmp = &myErrorJmp;
  47. if (setjmp(myErrorJmp.b) == 0) { /* to catch memory allocation errors */
  48. L->gt = luaH_new(L, 10);
  49. luaD_init(L, (stacksize == 0) ? DEFAULT_STACK_SIZE :
  50. stacksize+LUA_MINSTACK);
  51. luaS_init(L);
  52. luaX_init(L);
  53. luaT_init(L);
  54. #ifdef DEBUG
  55. luaB_opentests(L);
  56. #endif
  57. L->GCthreshold = L->nblocks*4;
  58. L->errorJmp = NULL;
  59. return L;
  60. }
  61. else { /* memory allocation error: free partial state */
  62. lua_close(L);
  63. return NULL;
  64. }
  65. }
  66. void lua_close (lua_State *L) {
  67. luaC_collect(L, 1); /* collect all elements */
  68. LUA_ASSERT(L->rootproto == NULL, "list should be empty");
  69. LUA_ASSERT(L->rootcl == NULL, "list should be empty");
  70. LUA_ASSERT(L->roottable == NULL, "list should be empty");
  71. luaS_freeall(L);
  72. luaM_free(L, L->stack);
  73. luaM_free(L, L->IMtable);
  74. luaM_free(L, L->refArray);
  75. luaM_free(L, L->Mbuffer);
  76. LUA_ASSERT(L->nblocks == 0, "wrong count for nblocks");
  77. luaM_free(L, L);
  78. LUA_ASSERT(L->Cbase == L->stack, "stack not empty");
  79. LUA_ASSERT(L != lua_state || memdebug_numblocks == 0, "memory leak!");
  80. LUA_ASSERT(L != lua_state || memdebug_total == 0,"memory leak!");
  81. }