lstate.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. ** $Id: lstate.c,v 1.33 2000/08/14 17:46: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 "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 : stacksize);
  47. luaS_init(L);
  48. luaX_init(L);
  49. luaT_init(L);
  50. if (put_builtin)
  51. luaB_predefine(L);
  52. L->GCthreshold = L->nblocks*4;
  53. L->errorJmp = NULL;
  54. return L;
  55. }
  56. else { /* memory allocation error: free partial state */
  57. lua_close(L);
  58. return NULL;
  59. }
  60. }
  61. #ifdef DEBUG
  62. extern lua_State *lua_state;
  63. #endif
  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 != lua_state || memdebug_numblocks == 0, "memory leak!");
  77. LUA_ASSERT(L != lua_state || memdebug_total == 0,"memory leak!");
  78. }