lua-users home
lua-l archive

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


Le 20 oct. 2012 à 06:06, Rena <hyperhacker@gmail.com> a écrit :

> Well, the main concern is that I'll be calling user-provided code,
> which might naively call print() or load a module that uses print()
> for debug output.

Alternatively to redefining print(), if you recompile your own Lua library, you can redirect the print() function to whatever you want by redefining the luai_writestring and luai_writeline macros in luaconf.h.

For example, in my luaconf.h file I replaced:
<<
/*
@@ luai_writestring/luai_writeline define how 'print' prints its results.
** They are only used in libraries and the stand-alone program. (The #if
** avoids including 'stdio.h' everywhere.)
*/
#if defined(LUA_LIB) || defined(lua_c)
#include <stdio.h>
#define luai_writestring(s,l)	fwrite((s), sizeof(char), (l), stdout)
#define luai_writeline()	(luai_writestring("\n", 1), fflush(stdout))
#endif
>>

with:
<<
/*
@@ luai_writestring/luai_writeline define how 'print' prints its results.
** They are only used in libraries and the stand-alone program. (The #if
** avoids including 'stdio.h' everywhere.)
** The flag CIM_LUA_CUSTOM_PRINT redirects print commands to functions provided externally.
*/
#if defined(CIM_LUA_CUSTOM_PRINT)
extern void CIMLuaPrintAppendString (void *L, const char* s);
extern void CIMLuaPrintLine (void *L);
#define luai_writestring(s,l)	CIMLuaPrintAppendString(L,s)
#define luai_writeline()	CIMLuaPrintLine (L)

#elif defined(LUA_LIB) || defined(lua_c)
#include <stdio.h>
#define luai_writestring(s,l)	fwrite((s), sizeof(char), (l), stdout)
#define luai_writeline()	(luai_writestring("\n", 1), fflush(stdout))
#endif
>>

Notes:
- this is for Lua 5.2; I guess that 5.1 has similar macros
- CIM is just the Prefix for my library (nothing subtle or mysterious here ;-)
- I had to use "void *L" parameters in place of "lua_State *L" because lua_State is not defined at the luaconf.h level

Jean-Luc