lua-users home
lua-l archive

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


Hi,

> What I would like to do is to overload a registration of a c function.
> 
> What I would like to write in c is something like:
> 
> int myhandler( lua_State* L )
> {
>   int n_returns = 0;
>   if(strcmp(lua_tostring(L,0),"foo")==0)
>   {
>     ... do stuff for function foo
>   }
>   else if(strcmp(lua_tostring(L,0),"fun")==0)
>   {
>     ... do stuff for function fun
>   }
>   return n_returns;    /* would be set by something above
> }
> 
> So I envision lua_tostring(L,0) retrieving something analogous to what
> argv[0] is in the parameters to a program - the program name.  That way
> I could write the following registrations:
> 
>   lua_register(L,"foo",myhandler);
>   lua_register(L,"fun",myhandler);

You can do that with C closures as follows (untested code):

    int myhandler( lua_State* L )
    {
        int n_returns = 0;
		/* get 'personality' from closure value */
        const char *name = lua_tostring(L, -1);
        if(strcmp(name,"foo")==0) {
        ... do stuff for function foo
        } else if(strcmp(name,"fun")==0) {
        ... do stuff for function fun
        }
        return n_returns;    /* would be set by something above
    }
    
	/* define global "foo" */
    lua_pushstring(L, "foo");
    lua_pushcclosure(L, myhandler, 1);
    lua_setglobal(L, "foo")

	/* define global "fun" */
    lua_pushstring(L, "fun");
    lua_pushcclosure(L, myhandler, 1); 
    lua_setglobal(L, "fun")

Whenever a C closure is called, it receives the values enclosed as it's
last parameters. Thus, the two functions defined above will receive
different closure values as their last parameter, enabling the C
implementation to distinguish between the "foo" and "fun" personalities. 

Regards,
Diego.