lua-users home
lua-l archive

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


>Let's say i want to replace print by another c function (printc), 
>but depending on the input of print.
>
>the way i would do it now is the following:
>
>lua_register(State, "_____myprint",printc);
>lua_dostring(State,
>"do "
>" local _print,myprint=print,_____myprint "
>" _____myprint=nil"
>" function print(...) "
>"   if condition then myprint(unpack(arg)) "
>"   else print(unpack(arg)) "
>" end "
>"end")

I'm probably missing something, but if the condition is testable in C, then
a simple solution is redefine print as follows:

 static int myprint(lua_State* L)
 {
	 if (condition)
		 lua_pushcfunction(printc);
	 else
		 lua_getglobal(L,"_print");
	 lua_insert(L,1);
	 lua_call(L,lua_gettop(L)-1,LUA_MULTRET);
	 return 0;
 }

and in main

	lua_getlobal(L,"print");
	lua_setlobal(L,"_print");
	lua_pushcfunction(myprint);
	lua_setglobal(L,"print");

You can avoid the use of _print by using an upvalue in myprint.
--lhf