Advertisement
robn

gctest.c

May 26th, 2012
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <assert.h>
  3.  
  4. #include "lua.h"
  5. #include "lauxlib.h"
  6.  
  7. static int num_allocated = 0;
  8.  
  9. static int l_newthing(lua_State *l) {
  10.     lua_newuserdata(l, sizeof(void*));
  11.  
  12.     lua_getglobal(l, "metatable");
  13.     lua_setmetatable(l, -2);
  14.  
  15.     num_allocated++;
  16.     printf("  alloc: %d objects\n", num_allocated);
  17.  
  18.     return 1;
  19. }
  20.  
  21. static int l_gc(lua_State *l) {
  22.     num_allocated--;
  23.     printf("dealloc: %d objects\n", num_allocated);
  24.  
  25.     return 0;
  26. }
  27.  
  28. int main(int argc, char **argv) {
  29.     lua_State *l = luaL_newstate();
  30.  
  31.     lua_newtable(l);
  32.     lua_pushstring(l, "__gc");
  33.     lua_pushcfunction(l, l_gc);
  34.     lua_rawset(l, -3);
  35.     lua_setglobal(l, "metatable");
  36.  
  37.     lua_pushcfunction(l, l_newthing);
  38.     lua_setglobal(l, "newthing");
  39.  
  40.     assert(!luaL_loadstring(l, "for i = 1,10000 do newthing() end"));
  41.     lua_call(l, 0, 1);
  42.  
  43.     printf("done! inspect the process, then press enter to finish\n");
  44.     getc(stdin);
  45.  
  46.     lua_close(l);
  47.  
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement