load default.nut for all scripts, have own roottable for console and load console...
[supertux.git] / src / scripting / wrapper_util.cpp
index 605ff1b..a24a5ac 100644 (file)
@@ -1,9 +1,31 @@
+//  $Id$
+//
+//  SuperTux
+//  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
+//
+//  This program is free software; you can redistribute it and/or
+//  modify it under the terms of the GNU General Public License
+//  as published by the Free Software Foundation; either version 2
+//  of the License, or (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, write to the Free Software
+//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+
 #include <config.h>
 
 #include <stdexcept>
 #include <sstream>
 #include "wrapper_util.hpp"
 
+namespace Scripting
+{
+
 std::string squirrel2string(HSQUIRRELVM v, int i)
 {
   std::ostringstream os;
@@ -180,4 +202,37 @@ void print_squirrel_stack(HSQUIRRELVM v)
     printf("--------------------------------------------------------------\n");
 }
 
-/* EOF */
+static SQInteger squirrel_read_char(SQUserPointer file)
+{
+  std::istream* in = reinterpret_cast<std::istream*> (file);
+  char c = in->get();
+  if(in->eof())
+    return 0;
+  return c;
+}
+
+void compile_script(HSQUIRRELVM vm, std::istream& in, const std::string& sourcename)
+{
+  if(SQ_FAILED(sq_compile(vm, squirrel_read_char, &in, sourcename.c_str(), true)))
+    throw SquirrelError(vm, "Couldn't parse script");  
+}
+
+void compile_and_run(HSQUIRRELVM vm, std::istream& in, const std::string& sourcename)
+{
+  compile_script(vm, in, sourcename);
+  
+  int oldtop = sq_gettop(vm);
+
+  try {
+    sq_pushroottable(vm);
+    if(SQ_FAILED(sq_call(vm, 1, false)))
+      throw SquirrelError(vm, "Couldn't start script");
+  } catch(...) {
+    sq_settop(vm, oldtop);
+    throw;
+  }
+
+  sq_settop(vm, oldtop);
+}
+
+}