/*!
  \file
  \brief Luabind の初期化

  \author Satofumi KAMIMURA

  $Id: luabindInit.cpp 1359 2009-10-03 06:07:13Z satofumi $
*/

#include "luabindInit.h"
#include "LuaHandler.h"
#include "log_printf.h"
#include <luabind/luabind.hpp>
#include <sstream>

using namespace qrk;
using namespace std;


namespace
{
  bool initialized_ = false;


  int outputError(lua_State* lua)
  {
    lua_Debug d;
    lua_getstack(lua, 1, &d);
    lua_getinfo(lua, "Sln", &d);
    string error_message = lua_tostring(lua, -1);
    lua_pop(lua, 1);
    stringstream where_message;
    where_message << d.short_src << ":" << d.currentline;

    if (d.name != 0) {
      where_message << "(" << d.namewhat << " " << d.name << ")";
    }
    string output_message = where_message.str() + " " + error_message;
    lua_pushstring(lua, output_message.c_str());
    log_printf("%s\n", output_message.c_str());

    return 1;
  }
};


lua_State* qrk::luabindInit(lua_State* lua, bool force)
{
  if (! lua) {
    lua = LuaHandler::pointer();
  }

  if (force || (! initialized_)) {
    luabind::open(lua);
    luabind::set_pcall_callback(&outputError);
  }

  initialized_ = true;
  return lua;
}
