lstate.c 2.3 KB

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