getsize.c

changeset 0
dc6c564e4d0a
child 1
fcb41eb42326
equal deleted inserted replaced
-1:000000000000 0:dc6c564e4d0a
1 /* lua-getsize
2 Author: (C) 2009 Matthew Wild
3 License: MIT/X11 license
4 Description: Adds a debug.getsize() function which
5 returns the size in bytes of a Lua object
6 */
7
8 #include <stdio.h>
9
10 #include <lua.h>
11 #include <lstate.h>
12 #include <lobject.h>
13 #include <lfunc.h>
14
15 int debug_getsize(lua_State* L)
16 {
17 TValue* o = L->base;
18 switch (o->tt) {
19 /* Container types */
20 case LUA_TTABLE: {
21 Table *h = hvalue(o);
22 printf("Size of array: %p\n", h->array);
23 lua_pushinteger(L, sizeof(Table) + sizeof(TValue) * h->sizearray +
24 sizeof(Node) * sizenode(h));
25 break;
26 }
27 case LUA_TFUNCTION: {
28 Closure *cl = clvalue(o);
29 lua_pushinteger(L, (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) :
30 sizeLclosure(cl->l.nupvalues));
31 break;
32 }
33 case LUA_TTHREAD: {
34 lua_State *th = thvalue(o);
35 lua_pushinteger(L, sizeof(lua_State) + sizeof(TValue) * th->stacksize +
36 sizeof(CallInfo) * th->size_ci);
37 break;
38 }
39 case LUA_TPROTO: {
40 Proto *p = pvalue(o);
41 lua_pushinteger(L, sizeof(Proto) + sizeof(Instruction) * p->sizecode +
42 sizeof(Proto *) * p->sizep +
43 sizeof(TValue) * p->sizek +
44 sizeof(int) * p->sizelineinfo +
45 sizeof(LocVar) * p->sizelocvars +
46 sizeof(TString *) * p->sizeupvalues);
47 break;
48 }
49 /* Non-containers */
50 case LUA_TUSERDATA: {
51 lua_pushnumber(L, uvalue(o)->len);
52 break;
53 }
54 case LUA_TLIGHTUSERDATA: {
55 lua_pushnumber(L, sizeof(void*));
56 break;
57 }
58 case LUA_TSTRING: {
59 TString *s = rawtsvalue(o);
60 lua_pushinteger(L, sizeof(TString) + s->tsv.len + 1);
61 break;
62 }
63 case LUA_TNUMBER: {
64 lua_pushinteger(L, sizeof(lua_Number));
65 break;
66 }
67 case LUA_TBOOLEAN: {
68 lua_pushinteger(L, sizeof(int));
69 break;
70 }
71 default: return 0;
72 }
73 return 1;
74 }
75
76 int luaopen_getsize(lua_State* L)
77 {
78 lua_getglobal(L, "debug");
79 lua_pushcfunction(L, debug_getsize);
80 lua_setfield(L, -2, "getsize");
81 return 0;
82 }

mercurial