How to replace Lua default error printing?

I use Lua as a script language in a Windows application. Due to the structure of the application, the stream io is not used in the printout, for example, stdoutand stderror.

I managed to override Lua printto fit into my structure ...

lua_register(L,"print", cs_print);

... but how do I override the entire error debug printouts without using threads? I need to handle this in a function (similarly print).

+4
source share
2 answers

After a lot of Google, I came up with this solution to extract compiler and runtime error messages, and also to redirect the standard Lua print function.

++ Builder, , , . script TScriptLua Lua script, std:: map .

// list for mapping Lua state with object pointers.
static std::map<lua_State*,TScriptLua*> LuaObjMap;

- Lua.

extern "C" {

   // Inline to map Lua state pointer to object pointer
   static inline TScriptLua* GetScriptObject(lua_State* L) {
     return LuaObjMap.find(L)->second;
   }

Lua. (f) - Out(), char .

   // New Lua print function
   static int cs_print (lua_State *L) {

     // Map Lua state to object
     TScriptLua* f = GetScriptObject(L);

     if (f) {
       int count = lua_gettop(L);
       for (int i=1; i <= count; ++i) {
         const char *str = lua_tostring(L, i); // Get string
         size_t len = lua_rawlen(L,i);         // Get string length

         // Output string.
         f->Out(str,len);
       }
     }

     return 0;
   }

, / . Lua, f- > Out .

   // Error print routine
   static int cs_error(lua_State *L, char *msg) {

     // Map Lua state to object
     TScriptLua* f = GetScriptObject(L);

     // Get error message
     AnsiString m = String(msg) + " " + String(lua_tostring(L, -1));

     // "print" error message
     f->Out(m.c_str(),m.Length());

     // Clenaup Lua stack
     lua_pop(L, 1);

     return 0;
   }

 } // <--- End extern C

. Lua . script Rich Edit luaL_loadbuffer(), script lua_pcall().

void __fastcall TScriptLua::Compile(void) {

   // Create new Lua state
   lua_State *L = luaL_newstate();

   // Store mapping Lua state --> object
   LuaObjMap.insert( std::pair<lua_State*,TScriptLua*>(L,this) );

   // Override Lua Print
   lua_register(L,"print",  cs_print);

   // Load and compile script
   AnsiString script(Frame->Script_RichEdit->Text);
   if (luaL_loadbuffer(L,script.c_str(),script.Length(),AnsiString(Name).c_str()) == 0) {
     if (lua_pcall(L, 0, 0, 0))        // Run loaded Lua script
       cs_error(L, "Runtime error: "); // Print runtime error
   } else {
     cs_error(L, "Compiler error: ");  // Print compiler error
   }

   // Close Lua state
   lua_close(L);

   // Remove Lua --> object mapping
   LuaObjMap.erase( LuaObjMap.find(L) );

 }

, . , TScriptLua, Lua.

+1

, Lua stderr, , luaL_newstate . Lua , , Lua , . . http://www.lua.org/source/5.2/lua.c.html#main .

+6

All Articles