[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Cannot redirect stderr
- From: Sergio Fadda <superatropo@...>
- Date: Fri, 13 Nov 2009 14:24:16 +0100
Hi.
I'm writing a standalone application (Win32... windowed) which integrates the LUA interpreter; the application uses LUA to export some features and I want to show console output in a separated window.
Here's, a small _sample_ program that highlights my problem:
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(int argc, char **argv)
{
FILE *out, *err;
lua_State *L = lua_open();
/* Stops collector during initialization */
lua_gc(L, LUA_GCSTOP, 0);
/* Initializes other modules */
luaL_openlibs(L);
/* Restarts garbage collector */
lua_gc(L, LUA_GCRESTART, 0);
out = freopen("out.txt", "w", stdout);
err = freopen("err.txt", "w", stderr);
luaL_dostring(L, "print(\"test1\")");
luaL_dostring(L, "error(\"test2\")");
fclose(out);
fclose(err);
return 0;
}
The first print("test1") is executed correctly (writes the string in file "out.txt"), but the second error("test2") didn't write anything (neither in "out.txt" nor in "err.txt").
Googling, I've found the following solution, but it doesn't work for me:
FILE **pf;
FILE *out = fopen("out.txt", "w");
FILE *err = fopen("err.txt", "w");
lua_getglobal(sm_luaState, "io");
lua_pushstring(sm_luaState, "open");
lua_gettable(sm_luaState, -2);
lua_getfenv(sm_luaState, -1);
lua_getglobal(sm_luaState, "io");
lua_pushstring(sm_luaState, "stdout");
lua_gettable(sm_luaState, -2);
pf = (FILE **)lua_touserdata(sm_luaState, -1);
*pf = out;
lua_rawseti(sm_luaState, -3, 2);
lua_pushstring(sm_luaState, "stderr");
lua_gettable(sm_luaState, -2);
pf = (FILE **)lua_touserdata(sm_luaState, -1);
*pf = err;
lua_rawseti(sm_luaState, -3, 0);
lua_pop(sm_luaState, 5);
luaL_dostring(L,
"print(\"test1\")");
luaL_dostring(L, "error(\"test2\")");
fclose(out);
fclose(err);
This solution doesn't work even the first print.
Does anybody can help me?
Thanks.