lua-users home
lua-l archive

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


On 25 Apr, Diego Nehab wrote:
> 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.
> 


Hmmm,  this makes sense.  It seems similar to what I have done so far. 

I register a series of constants (using lua_setglobal) one for each
entry point in my interface.  I assign them to a bunch of user data's
which are tagged as ltTestObjectMethod.  Then I set the "function" tag
method for this type of user data.  This way I get exactly what I want.

I can write in Lua:

list = anm_listdl()
append(list,anm_lens())

Now, as long as I have a global named append which is tagged
appropriately my tag function will get called and more to the point it
has the following stack:
  "append",<a listdl>,<a lens>
as long as my user data that I pushed is the string containing append.

Is there a reason why I should do it with upvalues rather than with this
tag function?

Clarify for me please, (I am a lua newbie), if I have a large set of
access points (around 5000) then I need a stack at least large enough to
hold all the globals that I will define right?

Thanks,
Mark.