lstate.c 2.3 KB

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