lstate.c 2.2 KB

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