lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 4/18/06, 陈果 <guo.chen.cn@gmail.com> wrote:
> Can anyone help me figure out why there's no output from the global_resolver
> when I index a global variable from the script ? Thanks!

My guess is that you have never defined a metatable for the globals table.

Unless some other bit of code in your program created a metatable for
the globals table, the globals table has no associated metatable. 
Your call to lua_getmetatable(L, -1) would returning 0 and push
nothing on the stack.  So after this line executed, the stack would
contain only the globals table you pushed from the line prior.  The
next six lines end up setting values on the globals table, not a
metatable.

Also note if your globals table did have a metatable, then your code
fragment would not leave the stack balanced.  lua_pop(L, 1) would
remove the metatable but not the globals table pushed on by
lua_pushvalue().

Greg F

>
> Hi, everyone.
>
> In my programme, I want to catch the index activity of the global table
> whenever it failed to get _G[name], so I can provide my userdata to that
> indexed global variable. But unfortunately I got a failure and I can't
> figure out the reason. Following is my code fragment:
>
>     static int global_resovler(lua_State *L)
>     {
>
>         printf("global resolver\n");
>         return 0;
>     }
>
>     // in the extension
>     // Registers the global resolver
>     lua_pushvalue(L, LUA_GLOBALSINDEX);
>     lua_getmetatable(L, -1);
>
>     lua_pushstring(L, "__index");
>     lua_pushcfunction(L, global_resovler);
>     lua_rawset(L, -3);
>     lua_pushstring(L, "__newindex");
>     lua_pushcfunction(L, global_resovler);
>     lua_rawset(L, -3);
>     lua_pop(L, 1);
>
> --
> Best Regards.
>
> Chen guo
> Tongji University, China