Index: trunk/src/lib/Makefile.am
===================================================================
--- trunk/src/lib/Makefile.am	(revision 8059)
+++ trunk/src/lib/Makefile.am	(revision 8061)
@@ -79,3 +79,4 @@
 	parser \
 	shell \
+	script_engine \
 	gui
Index: trunk/src/lib/event/event_handler.cc
===================================================================
--- trunk/src/lib/event/event_handler.cc	(revision 8059)
+++ trunk/src/lib/event/event_handler.cc	(revision 8061)
@@ -337,5 +337,5 @@
   else
   {
-    //SDL_WM_GrabInput(SDL_GRAB_ON);
+    SDL_WM_GrabInput(SDL_GRAB_ON);
     SDL_ShowCursor(SDL_DISABLE);
   }
Index: trunk/src/lib/script_engine/Makefile.am
===================================================================
--- trunk/src/lib/script_engine/Makefile.am	(revision 8061)
+++ trunk/src/lib/script_engine/Makefile.am	(revision 8061)
@@ -0,0 +1,26 @@
+MAINSRCDIR=../..
+include $(MAINSRCDIR)/defs/include_paths.am
+
+INCLUDES= -I../../../extern_libs
+
+noinst_LIBRARIES = libORXscript.a
+
+libORXscript_a_SOURCES =
+
+AM_CPPFLAGS= @LUA_INCLUDES@
+
+bin_PROGRAMS = account
+account_SOURCES = \
+                account.cc\
+                Script.cc
+
+
+
+account_LDADD = libORXscript.a -L../../../extern_libs @LUA_LIBS@
+
+#main_LDFLAGS =
+
+
+noinst_HEADERS = \
+                lunar.h\
+                Script.h
Index: trunk/src/lib/script_engine/OLD/LuaCallback.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/LuaCallback.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/LuaCallback.cc	(revision 8061)
@@ -0,0 +1,116 @@
+/*
+   orxonox - the future of 3D-vertical-scrollers
+
+   Copyright (C) 2004 orx
+
+   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, or (at your option)
+   any later version.
+
+   ### File Specific:
+   main-programmer: Silvan Nellen
+   co-programmer: ...
+*/
+
+//#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_
+
+#include "Script.h"
+#include "LuaCallback.h"
+#include "luaincl.h"
+#include "scriptable.h"
+
+#include <cassert>
+#include <string>
+#include <iostream>
+#include <stdio.h>
+
+namespace OrxScript
+{
+
+  /**
+   * @brief This function accually executes a method called by Lua.
+   * @param lua Since this function gets called by lua it has to have a lua_State as parameter
+   * @return the number of return values. (which can be found on the stack)
+   *
+   * For Lua doesn't know how to handle C++ objects it pushes the Objecttable (including the objectpointer) on top of the stack and
+   * calls this function.
+   *
+   * @todo handle an acces to a nonexistent (deleted) object
+   */
+  int luaCallback (lua_State *lua)
+  {
+
+    // Locate the psudo-index for the function number
+    int methodNumber = lua_upvalueindex (1);
+    int returnCount = 0;
+
+    bool functionSuccess = false;
+
+    // Check for the "this" table
+    if (lua_istable (lua, 1))
+    {
+      // Found the "this" table. The object pointer is at the index 0
+      lua_rawgeti (lua, 1, 0);
+
+      if (lua_islightuserdata (lua, -1))
+      {
+        // Found the pointer, need to cast it
+        Scriptable* thisPointer = (Scriptable*) lua_touserdata (lua, -1);
+
+        // Get the method index
+        int methodIndex = (int) lua_tonumber (lua, methodNumber);
+
+        // Reformat the stack so our parameters are correct
+        // Clean up the "this" table
+        lua_remove (lua, 1);
+        // Clean up the thisPointer pointer
+        lua_remove (lua, -1);
+
+        //debug
+        //std::cout<<thisPointer->whatIsThis()<<std::endl;
+
+        LuaScript* originScript = NULL;
+
+        lua_getglobal (lua, "this");
+
+        if (lua_istable (lua, 1))
+        {
+          // Found the "this" table. The object pointer is at the index 0
+          lua_rawgeti (lua, 1, 0);
+
+          if (lua_islightuserdata (lua, -1))
+          {
+            // Found the pointer, need to cast it
+            originScript = (LuaScript *) lua_touserdata (lua, -1);
+          }
+        }
+
+        if(originScript == NULL)
+        {//do something usefull
+        }
+        //debug
+        // std::cout<<originScript->whatIsThis()<<std::endl;
+
+        LuaVirtualMachine virtualMachine = originScript->getVirtualMachine();
+        //debug
+        //std::cout<<"test "<< thisPointer->methods(virtualMachine)<<std::endl;
+        // Check that the method is correct index
+        assert ((methodIndex <= thisPointer->methods(virtualMachine) ));
+        // Call the class
+        returnCount = thisPointer->scriptCalling ( virtualMachine, thisPointer->getFunctionAtIndex(methodIndex,virtualMachine));
+
+        functionSuccess = true;
+      }
+    }
+
+    if (functionSuccess == false)
+    {
+      lua_pushstring (lua, "luaCallback -> Failed to call the class function");
+      lua_error (lua);
+    }
+
+    // Number of return variables
+    return returnCount;
+  }
+}
Index: trunk/src/lib/script_engine/OLD/LuaCallback.h
===================================================================
--- trunk/src/lib/script_engine/OLD/LuaCallback.h	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/LuaCallback.h	(revision 8061)
@@ -0,0 +1,11 @@
+#ifndef __LUA_CALLBACK_H__
+#define __LUA_CALLBACK_H__
+
+struct lua_State;
+
+namespace OrxScript
+{
+  class LuaVirtualMachine;
+  int luaCallback (lua_State *lua);
+}
+#endif /* __LUA_CALLBACK_H__*/
Index: trunk/src/lib/script_engine/OLD/RestoreStack.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/RestoreStack.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/RestoreStack.cc	(revision 8061)
@@ -0,0 +1,46 @@
+/*
+   orxonox - the future of 3D-vertical-scrollers
+
+   Copyright (C) 2004 orx
+
+   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, or (at your option)
+   any later version.
+
+   ### File Specific:
+   main-programmer: ...
+   co-programmer: ...
+*/
+
+//#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_
+
+#include "RestoreStack.h"
+#include "luaincl.h"
+
+namespace OrxScript
+{
+
+  /**
+   * @brief Stores the stack and the index to the top element
+   *
+   * @param virtualMachine the virtual machine to save
+   */
+  LuaRestoreStack::LuaRestoreStack (LuaVirtualMachine& virtualMachine) : savedState (NULL)
+  {
+    savedState = (lua_State *) virtualMachine;
+    if (virtualMachine.isOk ())
+    {
+      savedTopIndex = lua_gettop (savedState);
+    }
+  }
+  /**
+  * @brief Restores the virtual machine
+  *
+  *
+  */
+  LuaRestoreStack::~LuaRestoreStack ()
+  {
+    lua_settop (savedState, savedTopIndex);
+  }
+}
Index: trunk/src/lib/script_engine/OLD/RestoreStack.h
===================================================================
--- trunk/src/lib/script_engine/OLD/RestoreStack.h	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/RestoreStack.h	(revision 8061)
@@ -0,0 +1,31 @@
+#ifndef __RESTORE_STACK_H__
+#define __RESTORE_STACK_H__
+
+
+#include "VirtualMachine.h"
+/// Forward declaration
+struct lua_State;
+
+namespace OrxScript
+{
+
+  //! Class to restore the stack to the way we found it.
+  class LuaRestoreStack
+  {
+  public:
+    /**
+     * @brief Stores the stack and the index to the top element
+     *
+     * @param virtualMachine the virtual machine to save
+     */
+    LuaRestoreStack (LuaVirtualMachine& virtualMachine);
+    virtual ~LuaRestoreStack (void);
+
+  protected:
+    lua_State* savedState;
+    int savedTopIndex;
+  };
+
+}
+
+#endif // __RESTORE_STACK_H__
Index: trunk/src/lib/script_engine/OLD/Script.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/Script.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/Script.cc	(revision 8061)
@@ -0,0 +1,491 @@
+#include <cassert>
+#include <string>
+#include <iostream>
+#include "luaincl.h"
+
+#include "Script.h"
+#include "RestoreStack.h"
+#include "This.h"
+#include "LuaCallback.h"
+
+// ---------------------------------------------------------------------------
+
+namespace OrxScript
+{
+
+#define BEGIN_LUA_CHECK(vm)   lua_State *state = (lua_State *) vm; \
+                              if (vm.isOk ()) {
+#define END_LUA_CHECK         }
+
+
+  /**
+   * @brief Constructor. Sets up the lua stack and the "this" table
+   *
+   *
+   *
+   */
+
+  LuaScript::LuaScript ()
+      : methodCount (0) , argumentCount (0), functionName()
+  {
+    virtualMachine.init();
+    lua_State *state = (lua_State *) virtualMachine;
+
+    if (virtualMachine.isOk ())
+    {
+      // Create a reference to the "this" table. Each reference is unique
+      lua_newtable (state);
+      thisReference = luaL_ref (state, LUA_REGISTRYINDEX);
+
+      // Save the "this" table to index 0 of the "this" table
+      LuaRestoreStack rs (virtualMachine);
+      lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
+      lua_pushlightuserdata (state, (void *) this);
+      lua_rawseti (state, -2, 0);
+    }
+
+  }
+
+
+  /**
+   * @brief Deconstructor
+   *
+   */
+
+  LuaScript::~LuaScript (void)
+  {
+    LuaRestoreStack rs (virtualMachine);
+
+    BEGIN_LUA_CHECK (virtualMachine)
+    // Get the reference "this" table
+    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
+
+    // Clear index 0
+    lua_pushnil (state);
+    lua_rawseti (state, -2, 0);
+    END_LUA_CHECK
+
+  }
+
+
+
+  /**
+   * @brief Compiles a given buffer. (reads it into the lua stack)
+   * @param pbBuffer buffer to compile
+   * @param size_t length of the buffer
+   *
+   * @return true if it succeeded
+   */
+
+  bool LuaScript::compileBuffer (unsigned char *pbBuffer, size_t szLen)
+  {
+    assert (pbBuffer != NULL && "LuaScript::compileBuffer ->  pbBuffer == NULL");
+    assert (szLen != 0 && "LuaScript::compileBuffer -> szLen == 0");
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    // Make sure we have the correct "this" table
+    LuaThis luaThis (virtualMachine, thisReference);
+
+    return virtualMachine.runBuffer (pbBuffer, szLen);
+  }
+
+
+  /**
+   * @brief Compiles a given file. (reads it into the lua stack)
+   * @param strFilename filename
+   *
+   * @return true if it succeeded
+   */
+
+  bool LuaScript::compileFile (const std::string& strFilename)
+  {
+    //assert (strFilename != NULL && "LuaScript::compileFile -> strFilename == NULL");
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    // Make sure we have the correct "this" table
+    LuaThis luaThis (virtualMachine, thisReference);
+
+    return virtualMachine.runFile (strFilename);
+  }
+
+
+  /**
+   * @brief Registers a function with Lua, the function will be registered in the "this" table
+   * @param strFuncName name of the function by which it goes by in lua
+   *
+   * @return the pseudoindex of the function
+   */
+
+  int LuaScript::registerFunction (const std::string& strFuncName)
+  {
+    //  assert (strFuncName != NULL && "LuaScript::registerFunction -> strFuncName == NULL");
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    int iMethodIdx = -1;
+
+    LuaRestoreStack rs (virtualMachine);
+
+    BEGIN_LUA_CHECK (virtualMachine)
+    iMethodIdx = ++methodCount;
+
+    // Register a function with the lua script. Added it to the "this" table
+    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
+
+    // Push the function and parameters
+    lua_pushstring (state, strFuncName.c_str());
+    lua_pushnumber (state, (lua_Number) iMethodIdx);
+    lua_pushcclosure (state, luaCallback, 1);
+    lua_settable (state, -3);
+
+    END_LUA_CHECK
+
+    return iMethodIdx;
+  }
+
+
+  /**
+   * @brief Selects a script function to run
+   * @param  strFuncName name of the function to run
+   *
+   * @return true on success
+   */
+  bool LuaScript::selectScriptFunction (const std::string& strFuncName)
+  {
+    //  assert (strFuncName != NULL && "LuaScript::selectScriptFunction -> strFuncName == NULL");
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    bool fSuccess = true;
+
+    BEGIN_LUA_CHECK (virtualMachine)
+    // Look up function name
+    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
+    lua_pushstring (state, strFuncName.c_str());
+    lua_rawget (state, -2);
+    lua_remove (state, -2);
+
+    // Put the "this" table back
+    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
+
+    // Check that we have a valid function
+    if (!lua_isfunction (state, -2))
+    {
+      fSuccess = false;
+      lua_pop (state, 2);
+    }
+    else
+    {
+      argumentCount = 0;
+      functionName = strFuncName;
+    }
+    END_LUA_CHECK
+
+    return fSuccess;
+  }
+
+
+  /**
+   * @brief Checks to see if a function exists
+   * @param  functionName  Function name
+   *
+   * @return true if the function exists
+   */
+  bool LuaScript::scriptHasFunction (const std::string& functionName)
+  {
+    // printf("entered scriptHasFunction\n");
+
+    //  assert (strScriptName != NULL && "LuaScript::scriptHasFunction -> strScriptName == NULL");
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    // printf("assertions passed\n");
+
+    LuaRestoreStack rs (virtualMachine);
+
+    bool fFoundFunc = false;
+
+    BEGIN_LUA_CHECK (virtualMachine)
+    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
+    lua_pushstring (state, functionName.c_str());
+    lua_rawget (state, -2);
+    lua_remove (state, -2);
+
+    if (lua_isfunction (state, -1))
+    {
+      fFoundFunc = true;
+    }
+    END_LUA_CHECK
+
+    return fFoundFunc;
+
+  }
+
+
+  /**
+   * @brief Adds a parameter to the parameter list
+   * @param  string  string to be added as parameter for a function.
+   *
+   */
+
+  void LuaScript::addParam (const std::string& string)
+  {
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    BEGIN_LUA_CHECK (virtualMachine);
+    lua_pushstring (state, string.c_str());
+    ++argumentCount;
+    END_LUA_CHECK;
+  }
+
+
+  /**
+   * @brief Adds a parameter to the parameter list
+   * @param  iInt  integer to be added as parameter for a function.
+   *
+   */
+
+  void LuaScript::addParam (int iInt)
+  {
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    BEGIN_LUA_CHECK (virtualMachine)
+    lua_pushnumber (state, (lua_Number) iInt);
+    ++argumentCount;
+    END_LUA_CHECK
+  }
+
+
+  /**
+   * @brief Adds a parameter to the parameter list
+   * @param  fFloat  float to be added as parameter for a function.
+   *
+   */
+  void LuaScript::addParam (float fFloat)
+  {
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    BEGIN_LUA_CHECK (virtualMachine)
+    lua_pushnumber (state, (lua_Number) fFloat);
+    ++argumentCount;
+    END_LUA_CHECK
+  }
+
+
+  /**
+   * @brief Runs the selected script function
+   * @param  nReturns the count of return values
+   *
+   * @return true on success
+   */
+  bool LuaScript::run (int nReturns /* = 0 */)
+  {
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+    // At this point there should be a parameters and a function on the
+    // Lua stack. Each function get a "this" parameter as default and is
+    // pushed onto the stack when the method is selected
+
+    bool fSuccess = virtualMachine.callFunction (argumentCount + 1, nReturns);
+
+    if (fSuccess == true && nReturns > 0)
+    {
+      // Check for returns
+      handleReturns (virtualMachine, functionName);
+      lua_pop ((lua_State *) virtualMachine, nReturns);
+    }
+
+    return fSuccess;
+  }
+
+
+  /**
+   * @brief This function adds an object to a script so that the object is accessable from within the luascript.
+   *
+   * @param scriptable the scriptable object to add.
+   * @param strObjName the name that the object goes by in the script.
+   * @param luaScript  the script to which the scrtiptable is added
+   *
+   * @return a lua reference to the added object
+   *
+   *
+   *
+   */
+
+  int LuaScript::addScriptableToScript(Scriptable* scriptable, const std::string& strObjName)
+  {
+
+    lua_State *state = (lua_State *) (this->virtualMachine);
+
+    if(strObjName.compare(std::string("this")) != 0)
+    {
+      if (virtualMachine.isOk ())
+      {
+        /*create object table*/
+        // Create a reference to the "object" table and set a name for the reference. Each reference is unique
+
+        lua_newtable (state);
+        int  objRef = luaL_ref (state, LUA_REGISTRYINDEX);
+        lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
+        lua_setglobal (state, strObjName.c_str());
+
+
+        // Save the "object" table to index 0 of the "object" table
+        LuaRestoreStack rs(virtualMachine);
+        lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
+        lua_pushlightuserdata (state, scriptable);
+        lua_rawseti (state, -2, 0);
+
+        if(! addScriptableToList(scriptable,objRef))
+          std::cout<<"scriptable not added"<<std::endl;
+        if(!(scriptable->scriptableAdded(this,thisReference,objRef)))
+          std::cout<<"scriptableAdded returned false"<<std::endl;
+
+        return objRef;
+      }
+    }
+
+    return -1;
+
+  }
+
+
+
+  /**
+   * @brief Add the function to a scriptable in the Script
+   * @param strFuncName name of the function by which it goes by in lua
+   * @param toScriptable reference to the scriptable the function should be associated with
+   * @param methodIndex index of the last function.
+   *
+   * @return the pseudoindex of the function, -1 on failure
+   */
+
+  int LuaScript::addFunctionToScriptable(const std::string& strFuncName, int toScriptable, int lastMethodIndex)
+  {
+    //  assert (strFuncName != NULL && "LuaScript::registerFunction -> strFuncName == NULL");
+    assert (virtualMachine.isOk () && "VM Not OK");
+
+
+    //get the last method index from the Script
+    Scriptable* scriptable = getScriptableByReference(toScriptable);
+    int iMethodIdx = -1;
+
+    if(scriptable)
+    {
+      LuaRestoreStack rs (virtualMachine);
+
+      BEGIN_LUA_CHECK (virtualMachine)
+      // Register a function with the lua script. Added it to the "toScrtiptable" table
+      lua_rawgeti (state, LUA_REGISTRYINDEX, toScriptable);
+
+      if (lua_istable (state, 1))
+      {
+        iMethodIdx = ++lastMethodIndex;
+
+        // Push the function and parameters
+        lua_pushstring (state, strFuncName.c_str());
+        lua_pushnumber (state, (lua_Number) iMethodIdx);
+        lua_pushcclosure (state, luaCallback, 1);
+        lua_settable (state, -3);
+      }
+      END_LUA_CHECK
+
+    }
+    return iMethodIdx;
+  }
+
+
+  Scriptable* LuaScript::getScriptableByReference(int scrptblRef)
+  {
+
+    bool notFound = true;
+    std::list<Scrptbl>::iterator it = scriptableList.begin();
+
+    while(notFound && it != scriptableList.end() )
+    {
+      if((*it).scriptableRef == scrptblRef)
+      {
+        notFound = false;
+        return (*it).scriptable;
+      }
+      it++;
+    }
+
+
+    if(notFound)
+      return NULL;
+
+  }
+
+  int LuaScript::getReferenceByScriptable(Scriptable* scrptbl)
+  {
+    bool notFound = true;
+
+    std::list<Scrptbl>::iterator it = scriptableList.begin();
+
+    while(notFound && it != scriptableList.end() )
+    {
+      if((*it).scriptable == scrptbl)
+      {
+        notFound = false;
+        return (*it).scriptableRef;
+      }
+      it++;
+    }
+    if(notFound)
+      return -1;
+  }
+
+  bool LuaScript::addScriptableToList(Scriptable* scrptbl, int scriptableRef)
+  {
+    if(scrptbl)
+    {
+      if(getReferenceByScriptable(scrptbl) == -1) // Script isn't there yet
+      {
+        Scrptbl scriptableTmp;
+        scriptableTmp.scriptable = scrptbl;
+        scriptableTmp.scriptableRef = scriptableRef;
+        scriptableList.push_back(scriptableTmp);
+        return true;
+      }
+    }
+
+    return false;
+
+  }
+
+  bool LuaScript::removeScriptableFromList(Scriptable* toRemove)
+  {
+    if(toRemove)
+    {
+      int scrptbl = getReferenceByScriptable(toRemove);
+
+      if(scrptbl != -1)// if the scriptable is on the list
+      {
+        std::list<Scrptbl>::iterator it = scriptableList.begin();
+
+        while((*it).scriptable != toRemove && it != scriptableList.end() )
+        {
+          it++;
+        }
+
+        if(it != scriptableList.end())
+        {
+          scriptableList.erase(it);
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+
+  bool LuaScript::removeScriptableFromList(int scriptable)
+  {
+    return removeScriptableFromList(getScriptableByReference(scriptable));
+  }
+
+
+  char LuaScript::whatIsThis()
+  {
+    char result = 'l';
+    return result;
+  }
+}
+
Index: trunk/src/lib/script_engine/OLD/Script.h
===================================================================
--- trunk/src/lib/script_engine/OLD/Script.h	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/Script.h	(revision 8061)
@@ -0,0 +1,92 @@
+#ifndef __LUA_SCRIPT_BASE_H__
+#define __LUA_SCRIPT_BASE_H__
+
+#include <string>
+
+#include "VirtualMachine.h"
+#include "scriptable.h"
+
+namespace OrxScript
+{
+
+  struct Scrptbl
+  {
+    Scriptable* scriptable;
+    int scriptableRef;
+  };
+
+  class LuaScript
+  {
+  public:
+    LuaScript ();
+    virtual ~LuaScript (void);
+
+
+    void init(LuaVirtualMachine& vm);
+
+    /* ------------------ Script related Functions ------------------ */
+
+    // Compile script into Virtual Machine
+    bool compileFile (const std::string& strFilename);
+    bool compileBuffer (unsigned char *pbBuffer, size_t szLen);
+
+    // Register function with Lua in the this table
+    int registerFunction (const std::string& strFuncName);
+
+
+    // Selects a Lua Script function to call
+    bool selectScriptFunction (const std::string& strFuncName);
+    void addParam (int iInt);
+    void addParam (float fFloat);
+    void addParam (const std::string& string);
+
+    // Runs the loaded script
+    bool run (int nReturns = 0);
+
+    // Checks on Virtual Machine script
+    bool scriptHasFunction (const std::string& strScriptName);
+
+    // Method indexing check
+    int methods (void) { return methodCount; }
+
+
+    // When the script calls a class method, this is called
+    virtual int scriptCalling (LuaVirtualMachine& vm, int iFunctionNumber) = 0;
+
+    // When the script function has returns
+    virtual void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc) = 0;
+
+
+
+    /* ------------------- Handle external Objects ------------------ */
+
+    void removeFromScript(int referenceToScriptable) {}
+    int addScriptableToScript(Scriptable* scriptbl,const std::string& name);  // name= name the scriptable goes by in lua
+    int addFunctionToScriptable(const std::string& strFuncName, int toScriptable, int lastMethodIndex);
+
+    //Handle the Scriptable List
+    Scriptable* getScriptableByReference(int scrptblRef);
+    int getReferenceByScriptable(Scriptable* scriptable);
+    bool addScriptableToList(Scriptable* scriptbl, int scriptableRef);
+    bool removeScriptableFromList(Scriptable* scriptable);
+    bool removeScriptableFromList(int scriptable);
+
+
+
+    /* ------------------ ... ------------------ */
+
+    LuaVirtualMachine& getVirtualMachine (void) { return virtualMachine; }
+    char whatIsThis();
+
+  protected:
+    int methodCount;
+    LuaVirtualMachine virtualMachine;
+    int thisReference;
+    int argumentCount;
+    std::string functionName;
+    std::list<Scrptbl> scriptableList;
+  };
+
+}
+
+#endif // __LUA_SCRIPT_BASE_H__
Index: trunk/src/lib/script_engine/OLD/This.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/This.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/This.cc	(revision 8061)
@@ -0,0 +1,49 @@
+/*
+   orxonox - the future of 3D-vertical-scrollers
+
+   Copyright (C) 2004 orx
+
+   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, or (at your option)
+   any later version.
+
+   ### File Specific:
+   main-programmer: Silvan Nellen
+   co-programmer: ...
+*/
+
+//#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_
+
+#include "This.h"
+#include "luaincl.h"
+
+namespace OrxScript
+{
+  LuaThis::LuaThis (LuaVirtualMachine& vm, int iRef) : oldReference (0), virtualMachine (vm)
+  {
+    lua_State *state = (lua_State *) vm;
+    if (vm.isOk ())
+    {
+      // Save the old "this" table
+      lua_getglobal (state, "this");
+      oldReference = luaL_ref (state, LUA_REGISTRYINDEX);
+
+      // replace it with our new one
+      lua_rawgeti(state, LUA_REGISTRYINDEX, iRef);
+      lua_setglobal (state, "this");
+    }
+  }
+
+  LuaThis::~LuaThis (void)
+  {
+    lua_State *state = (lua_State *) virtualMachine;
+    if (oldReference > 0 && virtualMachine.isOk ())
+    {
+      // Replace the old "this" table
+      lua_rawgeti(state, LUA_REGISTRYINDEX, oldReference);
+      lua_setglobal (state, "this");
+      luaL_unref (state, LUA_REGISTRYINDEX, oldReference);
+    }
+  }
+}
Index: trunk/src/lib/script_engine/OLD/This.h
===================================================================
--- trunk/src/lib/script_engine/OLD/This.h	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/This.h	(revision 8061)
@@ -0,0 +1,21 @@
+#ifndef __THIS_H__
+#define __THIS_H__
+
+#include "VirtualMachine.h"
+
+// Sets the "this" global table that scripts use
+namespace OrxScript
+{
+
+  class LuaThis
+  {
+  public:
+    LuaThis (LuaVirtualMachine& vm, int iRef);
+    virtual ~LuaThis (void);
+
+  protected:
+    int oldReference;
+    LuaVirtualMachine& virtualMachine;
+  };
+}
+#endif // __THIS_H__
Index: trunk/src/lib/script_engine/OLD/VirtualMachine.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/VirtualMachine.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/VirtualMachine.cc	(revision 8061)
@@ -0,0 +1,291 @@
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "luaincl.h"
+#include "VirtualMachine.h"
+namespace OrxScript
+{
+  // ---------------------------------------------------------------------------
+
+
+  //============================================================================
+  // int printMessage
+  //---------------------------------------------------------------------------
+  // Prints a message to the console
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // lua         IN       State variable
+  //
+  // Return
+  // ------
+  // Number of return varaibles on the stack
+  //
+  //============================================================================
+  static int printMessage (lua_State *lua)
+  {
+    assert (lua_isstring (lua,1));
+
+    const char *msg = lua_tostring (lua, 1);
+
+    // get caller
+    lua_Debug ar;
+    memset (&ar, 0, sizeof(ar));
+    lua_getstack (lua, 1, &ar);
+    lua_getinfo (lua, "Snl", &ar);
+
+    // debug output
+    const char *str = ar.source;
+    printf ("script: %s -- at %s(%d)\n", msg, str, ar.currentline);
+    return 0;
+  }
+
+  //============================================================================
+  // LuaVirtualMachine::LuaVirtualMachine
+  //---------------------------------------------------------------------------
+  // Constructor. Setups the default VM state
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  //
+  //
+  // Return
+  // ------
+  // None.
+  //
+  //============================================================================
+  LuaVirtualMachine::LuaVirtualMachine (void) : luaState (NULL)
+  {
+    machineIsOk = false;
+  }
+
+  //============================================================================
+  // LuaVirtualMachine::LuaVirtualMachine
+  //---------------------------------------------------------------------------
+  // Destructor. Closes the VM
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  //
+  //
+  // Return
+  // ------
+  // None.
+  //
+  //============================================================================
+  LuaVirtualMachine::~LuaVirtualMachine (void)
+  {
+    if (luaState != NULL)
+    {
+      lua_close (luaState);
+    }
+  }
+
+  //============================================================================
+  // LuaVirtualMachine::Panic
+  //---------------------------------------------------------------------------
+  // When things in Lua go wrong (ever called in protected mode??)
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // lua         IN       State variable
+  //
+  // Return
+  // ------
+  // None.
+  //
+  //============================================================================
+  void LuaVirtualMachine::panic (lua_State *lua)
+  {}
+
+  //============================================================================
+  // bool LuaVirtualMachine::init
+  //---------------------------------------------------------------------------
+  // Initialises the VM, open lua, makes sure things are OK
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // None.
+  //
+  // Return
+  // ------
+  // Success.
+  //
+  //============================================================================
+  bool LuaVirtualMachine::init (void)
+  {
+    // Open Lua!
+    if (isOk ()) destroy ();
+
+    luaState = lua_open ();
+
+    if (luaState)
+    {
+      machineIsOk = true;
+
+      // Load util libs into lua
+      luaopen_base (luaState);
+      luaopen_table (luaState);
+      luaopen_string (luaState);
+      luaopen_math (luaState);
+      luaopen_debug (luaState);
+      luaopen_io (luaState);
+      luaopen_loadlib (luaState);
+
+      // setup global printing (trace)
+      lua_pushcclosure (luaState, printMessage, 0);
+      lua_setglobal (luaState, "trace");
+
+      lua_atpanic (luaState, (lua_CFunction) LuaVirtualMachine::panic);
+
+      return true;
+    }
+
+    return false;
+  }
+
+  //============================================================================
+  // bool LuaVirtualMachine::destroy
+  //---------------------------------------------------------------------------
+  // Clears the current Lua state
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // None.
+  //
+  // Return
+  // ------
+  // Success.
+  //
+  //============================================================================
+  bool LuaVirtualMachine::destroy (void)
+  {
+    if (luaState)
+    {
+      lua_close (luaState);
+      luaState = NULL;
+      machineIsOk = false;
+    }
+    return true;
+  }
+
+
+  //============================================================================
+  // bool LuaVirtualMachine::runFile
+  //---------------------------------------------------------------------------
+  // Compiles and runs a lua script file
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // strFilename IN       Filename to compile and run
+  //
+  // Return
+  // ------
+  // Success.
+  //
+  //============================================================================
+  bool LuaVirtualMachine::runFile (const std::string& strFilename)
+  {
+    bool fSuccess = false;
+    int iErr = 0;
+
+    if ((iErr = luaL_loadfile (luaState, strFilename.c_str())) == 0)
+    {
+      // Call main...
+      if ((iErr = lua_pcall (luaState, 0, LUA_MULTRET, 0)) == 0)
+      {
+        fSuccess = true;
+      }
+    }
+
+    /* if (fSuccess == false)
+     {
+       if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
+     }
+    */
+    return fSuccess;
+  }
+
+  //============================================================================
+  // bool LuaVirtualMachine::runBuffer
+  //---------------------------------------------------------------------------
+  // Compiles and runs a pre-compiled data buffer
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // pbBuffer    IN       Buffer to run
+  // szLen       IN       Length of buffer
+  // strName     IN       Name of Buffer
+  //
+  // Return
+  // ------
+  // Success.
+  //
+  //============================================================================
+  bool LuaVirtualMachine::runBuffer (const unsigned char *pbBuffer, size_t szLen, const char *strName /* = NULL */)
+  {
+    bool fSuccess = false;
+    int iErr = 0;
+
+    if (strName == NULL)
+    {
+      strName = "Temp";
+    }
+
+    if ((iErr = luaL_loadbuffer (luaState, (const char *) pbBuffer, szLen, strName)) == 0)
+    {
+      // Call main...
+      if ((iErr = lua_pcall (luaState, 0, LUA_MULTRET, 0)) == 0)
+      {
+        fSuccess = true;
+      }
+    }
+
+    /* if (fSuccess == false)
+     {
+       if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
+     }
+    */
+    return fSuccess;
+
+  }
+
+  //============================================================================
+  // LuaVirtualMachine::callFunction
+  //---------------------------------------------------------------------------
+  // Calls a function that is already on the stack
+  //
+  // Parameter   Dir      Description
+  // ---------   ---      -----------
+  // nArgs       IN       Args that are aleady on the stack
+  // nReturns    IN       Number of expected returns (will be on the stack)
+  //
+  // Return
+  // ------
+  // Success.
+  //
+  //============================================================================
+  bool LuaVirtualMachine::callFunction (int nArgs, int nReturns /* = 0 */)
+  {
+    bool fSuccess = false;
+
+    if (lua_isfunction (luaState, -nArgs-1))
+    {
+      int iErr = 0;
+      iErr = lua_pcall (luaState, nArgs, nReturns, 0);
+
+      if (iErr == 0)
+      {
+        fSuccess = true;
+      }
+      /*else
+      {
+        if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
+      }
+      */
+    }
+
+    return fSuccess;
+  }
+}
Index: trunk/src/lib/script_engine/OLD/VirtualMachine.h
===================================================================
--- trunk/src/lib/script_engine/OLD/VirtualMachine.h	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/VirtualMachine.h	(revision 8061)
@@ -0,0 +1,43 @@
+#ifndef __LUA_VIRTUAL_MACHINE_H__
+#define __LUA_VIRTUAL_MACHINE_H__
+
+#include <string>
+
+struct lua_State;
+namespace OrxScript
+{
+  class LuaVirtualMachine
+  {
+  public:
+    LuaVirtualMachine (void);
+    virtual ~LuaVirtualMachine (void);
+
+    bool init(void);
+    bool destroy (void);
+
+    // Load and run script elements
+    bool runFile (const std::string& strFilename);
+    bool runBuffer (const unsigned char *pbBuffer, size_t szLen, const char *strName = NULL);
+
+    // C-Api into script
+    bool callFunction (int nArgs, int nReturns = 0);
+
+    // Get the state of the lua stack (use the cast operator)
+    lua_State* getState (void) const{ return luaState; }
+    operator lua_State* (void) const { return luaState; }
+
+    static void panic (lua_State *lua);
+
+    // Check if the VM is OK and can be used still
+    virtual bool isOk (void) { return machineIsOk; }
+
+    // For debugging
+    //void AttachDebugger (CLuaDebugger *dbg) { m_pDbg = dbg; }
+
+  protected:
+    lua_State* luaState;
+    bool machineIsOk;
+    // CLuaDebugger *m_pDbg;
+  };
+}
+#endif
Index: trunk/src/lib/script_engine/OLD/main.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/main.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/main.cc	(revision 8061)
@@ -0,0 +1,300 @@
+#include <iostream>
+#include <string>
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "luaincl.h"
+#include "VirtualMachine.h"
+#include "Script.h"
+#include "LuaCallback.h"
+#include "RestoreStack.h"
+#include "scriptable.h"
+
+
+using namespace OrxScript;
+
+//HACK !!!
+/**
+ * @brief This function adds an object to a script so that the object is accessable from within the luascript. this function is later included in LuaScript as a method
+ *
+ * @param scriptable the scriptable object to add.
+ * @param strObjName the name that the object goes by in the script.
+ * @param luaScript  the script to which the scrtiptable is added
+ *
+ * @return a reference to the added object
+ *
+ *
+ * @todo add this function as a method to LuaScript
+ */
+
+
+int addObjectToScript(Scriptable* scriptable, const std::string& strObjName, LuaScript& luaScript)
+{
+
+  lua_State *state = (lua_State *) (luaScript.getVirtualMachine());
+  LuaVirtualMachine& virtualMachine = luaScript.getVirtualMachine();
+
+  //if() TODO: check if strObjName isn't "this"
+  if (virtualMachine.isOk ())
+  {
+    /*create object table*/
+    // Create a reference to the "object" table and set a name for the reference. Each reference is unique
+
+    lua_newtable (state);
+    int  objRef = luaL_ref (state, LUA_REGISTRYINDEX);
+    lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
+    lua_setglobal (state, strObjName.c_str());
+
+
+    // Save the "object" table to index 0 of the "object" table
+    LuaRestoreStack rs(virtualMachine);
+    lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
+    lua_pushlightuserdata (state, scriptable);
+    lua_rawseti (state, -2, 0);
+
+
+
+    return objRef;
+  }
+
+}
+
+
+/**
+ * @brief This function adds a function to a scriptable object in the lua state so that the function is accessable from within the luascript. this function is later included in LuaScript as a method
+           *
+           * @param scriptableRef a reference to the scriptable object
+           * @param strFuncName the name that the function goes by in the script.
+           * @param luaScript  the script to which the function is added
+           *
+           * @returns the pseudoindex of the function (The first function added has index 0, the 2nd 1 and so on)
+           *
+           * @todo add this function as a method to LuaScript
+ */
+
+
+int addFunctionToScriptable(int scriptableRef, const std::string& strFuncName, LuaScript& luaScript)
+{
+  lua_State *state = (lua_State *) (luaScript.getVirtualMachine());
+  LuaVirtualMachine& vm = luaScript.getVirtualMachine();
+  int iMethodIdx = -1;
+
+  if (vm.isOk ())
+  {
+    /* Add function */
+    LuaRestoreStack rs (vm);
+    iMethodIdx = 0;
+    lua_rawgeti (state, LUA_REGISTRYINDEX, scriptableRef);
+    lua_pushstring (state, strFuncName.c_str());
+    lua_pushnumber (state, (lua_Number) iMethodIdx);
+    lua_pushcclosure (state, luaCallback, 1);
+    lua_settable (state, -3);
+  }
+
+  return iMethodIdx;
+}
+
+class objectOne : public Scriptable
+{
+public:
+  objectOne () : Scriptable ()
+  {
+  }
+
+  int scriptCalling (LuaVirtualMachine& vm, std::string functionName)
+  {
+    //switch (iFunctionNumber) //- methodBase) uncomment this when methodBase gets correclty set in the Scriptable class
+    if(functionName == "printNameOne")
+    {
+      //case 0:
+      return printNameOne (vm);
+    }
+
+    return 0;
+  }
+
+
+  int printNameOne(LuaVirtualMachine& vm)
+  {
+    std::cout<<"Hi I'm Object 1 !"<<std::endl;
+    return 0;
+  }
+
+  void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc)
+  {
+  }
+
+}
+;
+
+class objectTwo : public Scriptable
+{
+public:
+  objectTwo () : Scriptable ()
+  {
+    registerFunction(std::string("printNameTwo"));
+    // registerFunction(std::string("printHello"));
+
+  }
+
+  int scriptCalling (LuaVirtualMachine& vm, std::string functionName)
+  {
+    //switch (iFunctionNumber) //- m_iMethodBase) //TODO:find a way to determine the function number somehow: this works just incidentally
+    if(functionName == "printNameTwo")
+    {
+      //case 0:
+
+      return printNameTwo (vm);
+    }
+
+    return 0;
+  }
+
+
+  int printNameTwo(LuaVirtualMachine& vm)
+  {
+    std::cout<<"Hi I'm Object 2 !\n"<<std::endl;
+    return 0;
+  }
+
+  int printHello(LuaVirtualMachine& vm)
+  {
+    std::cout<<"Nice to meet you!\n"<<std::endl;
+    return 0;
+  }
+
+  void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc)
+  {
+  }
+
+}
+;
+
+
+
+
+class CMyScript : public LuaScript
+{
+public:
+  CMyScript () : LuaScript ()
+  {
+    // m_iMethodBase = registerFunction ("hello1");
+    //registerFunction ("hello2");
+    //registerFunction ("hello3");
+  }
+
+  int scriptCalling (LuaVirtualMachine& vm, int iFunctionNumber)
+  {
+    /*switch (iFunctionNumber - m_iMethodBase)
+    {
+      case 0:
+        return Hello1 (vm);
+      case 1:
+        return Hello2 (vm);
+      case 2:
+        return Hello3 (vm);
+    }
+
+    return 0;*/
+  }
+
+  int Hello1 (LuaVirtualMachine& vm)
+  {
+    printf ("Hellow (1)\n");
+    return 0;
+  }
+
+  int Hello2 (LuaVirtualMachine& vm)
+  {
+    lua_State *state = (lua_State *) vm;
+
+    int iNumber = (int) lua_tonumber (state, -2);
+    int iNumber2 = (int) lua_tonumber (state, -1);
+    printf ("Hellow (2) -> %d\n", iNumber);
+    printf ("Second argument was %d\n",iNumber2);
+    return 0;
+  }
+
+  int Hello3 (LuaVirtualMachine& vm)
+  {
+    lua_State *state = (lua_State *) vm;
+
+    int iNumber = (int) lua_tonumber (state, -1);
+    printf ("Hello (3) -> %d\n", iNumber);
+    lua_pushnumber (state, iNumber + 2);
+    return 1;
+  }
+
+
+  void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc)
+  {
+    if (strcmp (strFunc.c_str(), "divideMe") == 0)
+    {
+      // frames returns an answer of the stack
+      lua_State *state = (lua_State *) vm;
+      int itop = lua_gettop (state);
+      int iType = lua_type (state, -1);
+      const char *s = lua_typename (state, iType);
+      double fFrameCount = lua_tonumber (state, -1);
+
+      printf ("frame count = %f\n", fFrameCount);
+    }
+  }
+
+protected:
+  int m_iMethodBase;
+};
+
+//! main  test routine
+int main (int argc, const char** argv)
+{
+
+  std::cout << "== lua-testing environment ==\n" << std::endl;
+
+
+
+  CMyScript ms;
+
+  objectOne ob1;
+  objectTwo ob2;
+  //CMyScript ob1 (vm2);
+
+  //addObjectToScript(&ob1, "obOne", ms, "printNameOne");
+  int obTwoRef = ms.addScriptableToScript(&ob2, "object");
+  // ms.addFunctionToScriptable("printNameTwo",obTwoRef,-1);
+
+  ms.compileFile ("luascript1.lua");
+
+
+  int iTopS = lua_gettop ((lua_State *) ms.getVirtualMachine());
+
+
+  assert (ms.scriptHasFunction ("CountAndCall"));
+  assert (!ms.scriptHasFunction ("countAndCall"));
+  assert (!ms.scriptHasFunction ("test"));
+
+  ms.selectScriptFunction ("CountAndCall");
+  ms.addParam (2);
+  bool res = ms.run ();
+  printf("ms.run returned %b\n",res);
+
+  /* Debug Output
+  lua_State* state =  (lua_State *) (ms.vm());
+  lua_Debug debug;
+  //lua_getfield(state, LUA_GLOBALSINDEX, "CountAndCall" );
+  lua_getinfo( state, "Sl", &debug );
+  std::cout << debug.name<< std::endl;
+  */
+
+  /*ms.selectScriptFunction ("divideMe");
+  ms.addParam (33);
+  ms.run (1);
+
+  ms.selectScriptFunction ("returnToMe");
+  ms.addParam (10);
+  ms.run (0);
+  */
+  return 0 ;
+
+}
Index: trunk/src/lib/script_engine/OLD/scriptable.cc
===================================================================
--- trunk/src/lib/script_engine/OLD/scriptable.cc	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/scriptable.cc	(revision 8061)
@@ -0,0 +1,409 @@
+#include <cassert>
+#include <string>
+#include <iostream>
+
+#include <map>
+#include <list>
+
+#include "luaincl.h"
+#include "Script.h"
+#include "LuaCallback.h"
+#include "scriptable.h"
+
+// ---------------------------------------------------------------------------
+namespace OrxScript
+{
+  /**
+   * @brief Constructor
+   *
+   */
+  Scriptable::Scriptable ()
+  {
+  }
+
+  /**
+   * @brief Deconstructor
+   *
+   * The Deconstructor tells all the scripts, that it is part of, that it is deleted.
+   *
+   */
+  Scriptable::~Scriptable (void)
+  {
+    std::list<Script>::iterator it;
+    for(it = scriptList.begin();it != scriptList.end(); it++)
+    {
+      (*it).script->removeFromScript((*it).thisReference);
+    }
+
+  }
+
+
+  //Method indexing check
+  int Scriptable::methods (LuaVirtualMachine& virtualMachine)
+  {
+    LuaScript* script =(getScriptByVirtualMachine(virtualMachine))->script;
+    if(script)
+    {
+      int lastMethod = getLastMethodIndexByPointer(script);
+      if(lastMethod != -1)
+        return lastMethod;
+    }
+
+    return -1;
+  }
+
+
+  /**
+   * @brief  Tells the scriptable that it got added to a script
+   * @param  toScript a pointer to the script the object got added
+   * @param
+   * @param  reference a reference to the scriptable in that partilular script
+   *
+   *  The scriptable will register all its functions to the table at "reference"
+   *  with the script.
+   *
+   */
+
+  bool Scriptable::scriptableAdded(LuaScript* toScript, int toScriptRef, int reference)
+  {
+
+    bool success = true ;
+    if(!scriptIsInScriptList(toScript))// look if the scriptable isn't already added.
+      if(toScript)
+      {
+        Script newScript;
+        newScript.script = toScript;
+        newScript.scriptReference = toScriptRef;
+        newScript.thisReference = reference;
+        newScript.lastMethodIndex = -1;
+        newScript.methodBase = -1;
+
+        scriptList.push_back(newScript);
+
+        int methodIndex;
+        Script* tmpScript = getScriptByPointer(toScript);
+
+        //add all the functions to the script
+        std::list<std::string>::const_iterator it;
+
+        for(it = functionList.begin();it != functionList.end(); it++)
+        {
+
+          if(tmpScript)
+          {
+            methodIndex = toScript->addFunctionToScriptable(*it, tmpScript->thisReference, tmpScript->lastMethodIndex);
+
+
+            if(newScript.methodBase = -1)
+            {
+              if(methodIndex != -1)
+              {
+                std::cout<<"methodIndex is "<<methodIndex<<std::endl;
+                tmpScript->methodBase= methodIndex;
+                tmpScript->lastMethodIndex= methodIndex;
+                tmpScript->functionMap[newScript.methodBase] = *it;
+              }
+              else{success = false; break;}
+            }
+
+            else if(methodIndex != -1)
+            {
+
+              tmpScript->lastMethodIndex = methodIndex;
+              tmpScript->functionMap[newScript.lastMethodIndex] = *it;
+            }
+            else{success= false;break;}
+
+          }
+        }
+
+
+
+      }
+      else
+      {
+        success = false;
+      }
+
+    return success;
+
+  }
+
+
+
+  /**
+    * @brief  Register a function with the scriptable
+    * @param  functionName function name
+    *
+    *
+   */
+
+  void Scriptable::registerFunction(std::string functionName)
+  {
+    //check whether the function is already registered
+    std::list<std::string>::iterator it;
+    for(it = functionList.begin();it != functionList.end(); it++)
+    {
+      if((*it).compare(functionName) == 0)
+      {
+        break;
+      }
+
+    }
+
+    if(it == functionList.end()) // if the functoin wasn't found
+      functionList.push_back(functionName);
+  }
+
+
+  /**
+   * @brief  Get the function name of the function at index
+   * @param  index
+   *
+   * @return the function name on success.
+   *
+   * This function is used in the ScriptCalling function
+   */
+  std::string Scriptable::getFunctionAtIndex(int index, LuaVirtualMachine& virtualMachine)
+  {
+    lua_State * luaState = (lua_State* ) virtualMachine;
+
+    if(virtualMachine.isOk())
+    {
+      lua_getglobal (luaState, "this");
+
+      if (lua_istable (luaState, 1))
+      {
+        // Found the "this" table. The object pointer is at the index 0
+        lua_rawgeti (luaState, 1, 0);
+
+        if (lua_islightuserdata (luaState, -1))
+        {
+          // Found the pointer, need to cast it
+          LuaScript* thisPointer = (LuaScript *) lua_touserdata (luaState, -1);
+
+          if(thisPointer != NULL)
+          {
+            Script* script = getScriptByPointer(thisPointer);
+            if( script != NULL)
+            {
+              std::map<int, std::string>::const_iterator it = script->functionMap.find(index);
+              if(it != script->functionMap.end())//if found
+                return script->functionMap[index];
+            }
+
+          }
+        }
+      }
+    }
+    return "";
+  }
+
+
+  /**
+   * @brief Gets the lastMethod index associated with the LuaScript
+   * @param the luaScript
+   *
+   * @return  A lua reference to the last function of the Scriptable
+   *
+   *
+   */
+
+  int Scriptable::getLastMethodIndexByPointer(LuaScript* luaScript)
+  {
+    if( luaScript )
+    {
+      Script* script = (getScriptByPointer(luaScript));
+      if(script)
+      {
+        return (script->lastMethodIndex);
+      }
+    }
+
+    return -1;
+  }
+
+
+  /**
+   * @brief Gets the functionMap Associated with a LuaScript
+   * @param the LuaScript
+   *
+   * @return A pointer to the functionMap, NULL on failure
+   *
+   *
+   */
+
+  std::map<int, std::string>* Scriptable::getFunctionMapByPointer(LuaScript* scriptPointer)
+  {
+    bool notFound = true;
+    if(scriptPointer)
+    {
+      std::list<Script>::iterator it = scriptList.begin();
+
+
+      while(notFound && it !=scriptList.end() )
+      {
+        if((*it).script == scriptPointer)
+        {
+          notFound = false;
+          return &(it->functionMap);
+        }
+        it++;
+      }
+    }
+
+    if(notFound)
+      return NULL;
+
+  }
+
+
+  /**
+   * @brief Gets the internal representation of a LuaScript by its pointer.
+   * @param script the LuaScript
+   *
+   * @return returns the script if it was found, NULL else.
+   *
+   *
+   */
+
+  Script* Scriptable::getScriptByPointer(LuaScript* script)
+  {
+    bool notFound = true;
+
+    if(script)
+    {
+      std::list<Script>::iterator it = scriptList.begin();
+
+      while(notFound && it != scriptList.end() )
+      {
+        if((*it).script == script)
+        {
+          notFound = false;
+          return &(*it);
+        }
+        it++;
+      }
+
+    }
+    if(notFound)
+      return NULL;
+
+  }
+
+
+  /**
+   * @brief Extracts the Script out of the virtual machine
+   * @param virtualMachine the virtualMachine to search for the script
+   *
+   * @return The Script. If there was an error it returns NULL
+   *
+   *
+   */
+  Script* Scriptable::getScriptByVirtualMachine(LuaVirtualMachine& virtualMachine)
+  {
+
+    if(virtualMachine.isOk())
+    {
+      lua_State * luaState = (lua_State* ) virtualMachine;
+      lua_getglobal (luaState, "this");
+
+      if (lua_istable (luaState, 1))
+      {
+        // Found the "this" table. The object pointer is at the index 0
+        lua_rawgeti (luaState, 1, 0);
+
+        if (lua_islightuserdata (luaState, -1))
+        {
+          // Found the pointer, need to cast it
+          LuaScript* thisPointer = (LuaScript *) lua_touserdata (luaState, -1);
+          Script* script = getScriptByPointer(thisPointer);
+
+          if(script)
+            return script;
+          else
+            return NULL;
+        }
+      }
+    }
+
+
+  }
+
+
+  /**
+   * @brief Checks if "this" Scriptable is already registred with a LuaScript
+   * @param script The LuaScript
+   *
+   * @return true when the Scriptable is alreads registered with that script, flase else.
+   *
+   *
+   */
+  bool Scriptable::scriptIsInScriptList(LuaScript* script)
+  {
+    bool notFound = true;
+
+    if(script)
+    {
+      std::list<Script>::iterator it = scriptList.begin();
+
+
+      while( notFound && it !=scriptList.end() )
+      {
+        if((*it).script == script)
+        {
+          notFound = false;
+          break;
+        }
+        it++;
+      }
+
+    }
+    return !notFound;
+
+  }
+
+
+  /**
+   * @brief Removes a LuaScript from the scriptList
+   * @param deleted LuaScript that is about to be deleted
+   *
+   * This function has to be called int the destructor of the LuaScript.
+   *
+   *
+   */
+
+  void Scriptable::scriptDeleted(LuaScript* deleted)
+  {
+    if(deleted)
+    {
+      Script* script = getScriptByPointer(deleted);
+      if(script)
+      {
+        std::list<Script>::iterator it = scriptList.begin();
+
+
+        while((*it).script != deleted && it != scriptList.end() )
+        {
+          it++;
+        }
+
+        if(it != scriptList.end())
+        {
+          scriptList.erase(it);
+        }
+
+
+      }
+    }
+
+  }
+
+
+
+  char Scriptable::whatIsThis()
+  {
+    char result = 's';
+    return result;
+  }
+}
Index: trunk/src/lib/script_engine/OLD/scriptable.h
===================================================================
--- trunk/src/lib/script_engine/OLD/scriptable.h	(revision 8061)
+++ trunk/src/lib/script_engine/OLD/scriptable.h	(revision 8061)
@@ -0,0 +1,72 @@
+#ifndef __SCRIPTABLE_H__
+#define __SCRIPTABLE_H__
+
+#include <string>
+#include <map>
+#include <list>
+
+#include "VirtualMachine.h"
+
+namespace OrxScript
+{
+  class LuaScript;
+
+  //internal representation of a LuaScript
+  struct Script
+  {
+    int lastMethodIndex;
+    int methodBase;
+    int thisReference;
+    LuaScript* script;
+    int scriptReference; // reference to the script in its own lua_State
+    std::map<int, std::string> functionMap;
+  };
+
+  class Scriptable
+  {
+    friend class LuaScript;
+
+  public:
+    Scriptable (void);
+    virtual ~Scriptable (void);
+
+    // Method indexing check
+    int methods (LuaVirtualMachine& virtualMachine);
+    //int methods(){;return 1;} //BAD BAD HACK HACK HACK !!!!!!!!!!!!!!
+
+    char whatIsThis();
+
+    // When the script calls a class method, this is called
+    virtual int scriptCalling (LuaVirtualMachine& vm, std::string functionName) = 0;
+
+    // When the script function has returns
+    virtual void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc) = 0;
+
+    std::string getFunctionAtIndex(int index, LuaVirtualMachine& virtualMachine);
+
+  protected:
+    void registerFunction(std::string functionName);//Adds a function to the internal function list
+  private:
+    bool scriptableAdded(LuaScript* script, int scriptRef, int reference);
+    //void scriptableFunctionAdded(LuaScript* script, int reference);
+
+
+    Script* getScriptByPointer(LuaScript* script);
+    Script* getScriptByVirtualMachine(LuaVirtualMachine& virtualMachine);
+    std::map<int, std::string>* getFunctionMapByPointer(LuaScript* scriptPointer);
+    int getLastMethodIndexByPointer(LuaScript* script);
+
+
+    bool scriptIsInScriptList(LuaScript* script);
+
+    void scriptDeleted(LuaScript* deleted);
+
+
+
+    std::list<std::string> functionList;
+    std::list<Script> scriptList;
+  };
+
+}
+
+#endif // __SCRIPTABLE_H__
Index: trunk/src/lib/script_engine/Script.cc
===================================================================
--- trunk/src/lib/script_engine/Script.cc	(revision 8061)
+++ trunk/src/lib/script_engine/Script.cc	(revision 8061)
@@ -0,0 +1,187 @@
+#include "Script.h"
+
+
+Script::Script()
+{
+  returnCount = argumentCount = 0;
+
+  luaState = lua_open();
+
+  luaopen_base(luaState);
+  luaopen_table(luaState);
+  luaopen_io(luaState);
+  luaopen_string(luaState);
+  luaopen_math(luaState);
+  luaopen_debug(luaState);
+
+}
+
+
+Script::~Script()
+{
+  lua_setgcthreshold(luaState, 0);  // collected garbage
+  lua_close(luaState);
+}
+
+
+bool Script::loadFile(std::string& filename)
+ {
+
+   if(currentFile.length() != 0)
+     printf("Could not load %s because an other file is already loaded: %s\n",filename.c_str(), currentFile.c_str());
+
+   int error = luaL_loadfile (luaState, filename.c_str());
+
+   if(error == 0)
+   {
+     error = lua_pcall(luaState, 0, 0, 0);
+
+     if(error == 0)
+     {
+      currentFile = filename;
+      return true;
+     }
+     else
+     {
+      reportError(error);
+     }
+
+   }
+   else
+   {
+     reportError(error);
+   }
+
+   return false;
+ }
+
+ bool Script::executeFile()
+ {
+   if(currentFile.length() != 0)
+   {
+    int error = lua_pcall(luaState, 0, 0, 0);
+    if( error == 0)
+      return true;
+     else
+      {
+       reportError(error);
+       return false;
+      }
+   }
+   return false;
+ }
+
+ bool Script::selectFunction(std::string& functionName, int retCount)
+ {
+   lua_pushlstring(luaState, functionName.c_str(), functionName.size() );
+   lua_gettable(luaState, LUA_GLOBALSINDEX);
+
+   if(lua_isfunction( luaState , -1))
+   {
+     returnCount = retCount;
+     argumentCount = 0;
+     currentFunction = functionName;
+     return true;
+   }
+   else
+    return false;
+
+ }
+
+ //return number of returned values
+ bool Script::executeFunction()
+ {
+   if(currentFunction.length() != 0 )
+   {
+    int error = lua_pcall(luaState, argumentCount, returnCount,0);
+    if(error != 0)
+    {
+     reportError(error);
+     return false;
+    }
+    else
+    {
+      currentFunction.assign("");//a function gets unusable after beeing called for the first time
+      returnCount = argumentCount = 0;
+      return true;
+    }
+   }
+   else
+     printf("Error: no function selected.\n");
+ }
+
+
+ //overload this function to add different types
+ bool Script::pushParam(int param, std::string& toFunction)
+ {
+   if(currentFunction.compare(toFunction) == 0)
+   {
+     lua_pushnumber(luaState, (lua_Number) param);
+     argumentCount++;
+    return true;
+   }
+   else
+   {
+    printf("Couldn't add parameter because the wrong function is selected: %s instead of %s\n", currentFunction.c_str(), toFunction.c_str());
+    return false;
+   }
+
+ }
+
+
+ bool Script::pushParam(float param, std::string& toFunction)
+ {
+   if(currentFunction.compare(toFunction) == 0)
+   {
+     lua_pushnumber(luaState,(lua_Number) param);
+     argumentCount++;
+     return true;
+   }
+   else
+   {
+     printf("Couldn't add parameter because the wrong function is selected: %s instead of %s\n", currentFunction.c_str(), toFunction.c_str());
+     return false;
+   }
+
+ }
+
+ bool Script::pushParam(double param, std::string& toFunction)
+ {
+   if(currentFunction.compare(toFunction) == 0)
+   {
+     lua_pushnumber(luaState,(lua_Number) param);
+     argumentCount++;
+     return true;
+   }
+   else
+   {
+     printf("Couldn't add parameter because the wrong function is selected: %s instead of %s\n", currentFunction.c_str(), toFunction.c_str());
+     return false;
+   }
+
+ }
+
+ int Script::getReturnedInt()
+ {
+   if(returnCount > 0)
+   {
+     printf("int found");
+     if(lua_isnumber(luaState, 1))
+     {
+       printf("int found");
+       int returnValue = (int)lua_tonumber(luaState, 1);
+       returnCount--;
+     }
+   }
+ }
+
+
+ int Script::reportError(int error)
+ {
+ const char *msg = lua_tostring(luaState, -1);
+ if (msg == NULL) msg = "(error with no message)";
+ fprintf(stderr, "ERROR: %s\n", msg);
+ lua_pop(luaState, 1);
+ return error;
+ }
+
Index: trunk/src/lib/script_engine/Script.h
===================================================================
--- trunk/src/lib/script_engine/Script.h	(revision 8061)
+++ trunk/src/lib/script_engine/Script.h	(revision 8061)
@@ -0,0 +1,45 @@
+#ifndef _SCRIPT_H
+#define _SCRIPT_H
+
+
+#include <string>
+#include "base_object.h"
+
+#include "luaincl.h"
+
+
+class Script
+{
+  public:
+    Script();
+    ~Script();
+
+    bool loadFile(std::string& filename);
+    bool executeFile();
+
+    lua_State* getLuaState() const{return luaState;}
+
+    bool selectFunction(std::string& functionName, int retCount);
+    bool executeFunction();
+    bool pushParam(int param, std::string& toFunction);//overload this function to add different types
+    bool pushParam(float param, std::string& toFunction);
+    bool pushParam(double param, std::string& toFunction);
+    int  getReturnedInt();
+
+
+
+  private:
+
+    int reportError(int error);
+
+    lua_State*         luaState;         //!< The lua_State that the Script works on
+    std::string        currentFile;      //!< The file that is loaded in the script
+    std::string        currentFunction;  //!< The name of the current active function (the one that gets the pushed parameter)
+    int                argumentCount;    //!< Number of arguments for the current function
+    int                returnCount;      //!< Number of return values of the current function
+
+
+
+
+};
+#endif /* _SCRIPT_H */
Index: trunk/src/lib/script_engine/account.cc
===================================================================
--- trunk/src/lib/script_engine/account.cc	(revision 8061)
+++ trunk/src/lib/script_engine/account.cc	(revision 8061)
@@ -0,0 +1,104 @@
+
+#include <iostream>
+
+#include "luaincl.h"
+#include "lunar.h"
+#include "Script.h"
+
+    class Account {
+      lua_Number m_balance;
+    public:
+      static const char className[];
+      static Lunar<Account>::RegType methods[];
+
+      Account(lua_State *L)      { m_balance = luaL_checknumber(L, 1); }
+      Account(double balance=0)    : m_balance(balance) { }
+      int deposit (lua_State *L) { m_balance += luaL_checknumber(L, 1); return 0; }
+      int withdraw(lua_State *L) { m_balance -= luaL_checknumber(L, 1); return 0; }
+      int balance (lua_State *L) { lua_pushnumber(L, m_balance); return 1; }
+      ~Account() { printf("deleted Account (%p)\n", this); }
+    };
+
+    const char Account::className[] = "Account";
+
+
+    #define method(class, name) {#name, &class::name}
+
+    Lunar<Account>::RegType Account::methods[] = {
+      method(Account, deposit),
+      method(Account, withdraw),
+      method(Account, balance),
+      {0,0}
+    };
+
+
+    class Object {
+      public:
+        static const char className[];
+        static Lunar<Object>::RegType methods[];
+
+        Object(lua_State* L) {callCount = 0; }
+        Object(){callCount = 0;};
+        ~Object() { printf("deleted Object (%p)\n", this); }
+
+
+        int printName(lua_State* L)
+        {
+          callCount ++;
+          printf("Hi i'm object %p ! This is the %i. call.\n",this,callCount);
+          return 0;
+        }
+
+
+      private:
+        int callCount;
+
+    };
+
+    const char Object::className[] = "Object";
+
+    Lunar<Object>::RegType Object::methods[] = {
+      method(Object, printName),
+      {0,0}
+    };
+
+    int main(int argc, char *argv[])
+    {
+      Script script;
+
+      // Register classes with the script
+      Lunar<Account>::Register(&script);
+      Lunar<Object>::Register(&script);
+
+      Object* obj= new Object();
+      Account a;
+      Account *b = new Account(30);
+
+      // Add instances to the script
+      Lunar<Object>::insertObject(&script,obj,"Obj",true);
+      Lunar<Account>::insertObject(&script,&a,"a",false);
+      Lunar<Account>::insertObject(&script,b,"b",true);
+
+
+      std::string file(argv[1]);
+
+      if(script.loadFile(file))
+        printf("File %s succefully loaded\n", file.c_str());
+
+      //script.executeFile();
+
+      std::string main("main");
+      if( script.selectFunction(main,1))
+       printf("function %s selected\n",main.c_str());
+
+      script.pushParam(3.14159,main);
+      script.executeFunction();
+
+      int ret = script.getReturnedInt();
+      printf("main returned %i\n",ret);
+
+      //if(argc>1) lua_dofile(script.getLuaState(), argv[1]);
+
+      return 0;
+    }
+
Index: trunk/src/lib/script_engine/config.h
===================================================================
--- trunk/src/lib/script_engine/config.h	(revision 8061)
+++ trunk/src/lib/script_engine/config.h	(revision 8061)
@@ -0,0 +1,56 @@
+/* config.h.  Generated by configure.  */
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `dl' library (-ldl). */
+#define HAVE_LIBDL 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Name of package */
+#define PACKAGE "lua_test"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "lua_test"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "lua_test 0.0.1-alpha"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "lua_test"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "0.0.1-alpha"
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Version number of package */
+#define VERSION "0.0.1-alpha"
Index: trunk/src/lib/script_engine/luaincl.h
===================================================================
--- trunk/src/lib/script_engine/luaincl.h	(revision 8061)
+++ trunk/src/lib/script_engine/luaincl.h	(revision 8061)
@@ -0,0 +1,13 @@
+
+#ifndef __LUA_INCL_H__
+#define __LUA_INCL_H__
+
+
+extern "C" {
+#include <lua.h>
+#include <lualib.h>
+#include <lauxlib.h>
+}
+
+#endif /* __LUA_INCL_H__ */
+
Index: trunk/src/lib/script_engine/luna/account.cc
===================================================================
--- trunk/src/lib/script_engine/luna/account.cc	(revision 8061)
+++ trunk/src/lib/script_engine/luna/account.cc	(revision 8061)
@@ -0,0 +1,105 @@
+#include "luna.h"
+/*extern "C" {
+#include <lualib.h>
+}
+*/
+
+class Account
+{
+public:
+  static const char className[];
+  static const Luna<Account>::RegType Register[];
+
+  Account(lua_State* L)
+  {
+    /* constructor table at top of stack */
+    lua_pushstring(L, "balance");
+    lua_gettable(L, -2);
+    m_balance = lua_tonumber(L, -1);
+    lua_pop(L, 2); /* pop constructor table and balance */
+  }
+
+  int deposit(lua_State* L)
+  {
+    std::cout<<"deposit called"<<std::endl;
+    m_balance += lua_tonumber(L, -1);
+    lua_pop(L, 1);
+    return 0;
+  }
+  int withdraw(lua_State* L)
+  {
+    m_balance -= lua_tonumber(L, -1);
+    lua_pop(L, 1);
+    return 0;
+  }
+  int balance(lua_State* L)
+  {
+    lua_pushnumber(L, m_balance);
+    return 1;
+  }
+
+protected:
+  double m_balance;
+};
+
+const char Account::className[] = "Account";
+const Luna<Account>::RegType Account::Register[] =
+  {
+    {"deposit",  &Account::deposit},
+    {"withdraw", &Account::withdraw},
+    {"balance",  &Account::balance},
+    {0}
+  };
+
+class Euclid
+{
+public:
+  static const char className[];
+  static const Luna<Euclid>::RegType Register[];
+
+  Euclid(lua_State* L)
+  {}
+
+  int gcd(lua_State* L)
+  {
+    int m = static_cast<int>(lua_tonumber(L, -1));
+    int n = static_cast<int>(lua_tonumber(L, -2));
+    lua_pop(L, 2);
+
+    /* precondition: m>0 and n>0.  Let g=gcd(m,n). */
+    while( m > 0 )
+    {
+      /* invariant: gcd(m,n)=g */
+      if( n > m )
+      {
+        int t = m; m = n; n = t; /* swap */
+      }
+      /* m >= n > 0 */
+      m -= n;
+    }
+
+    lua_pushnumber(L, n);
+    return 1;
+  }
+};
+
+const char Euclid::className[] = "Euclid";
+const Luna<Euclid>::RegType Euclid::Register[] =
+  {
+    {"gcd", &Euclid::gcd},
+    {0}
+  };
+
+int main(int argc, char* argv[])
+{
+  lua_State* L = lua_open();
+  lua_baselibopen(L);
+  Luna<Account>::Register(L);
+ // Luna<Euclid>::Register(L);
+
+  lua_dofile(L, argv[1]);
+
+
+  lua_close(L);
+  return 0;
+}
Index: trunk/src/lib/script_engine/luna/account.lua
===================================================================
--- trunk/src/lib/script_engine/luna/account.lua	(revision 8061)
+++ trunk/src/lib/script_engine/luna/account.lua	(revision 8061)
@@ -0,0 +1,12 @@
+--
+-- Luna Account example
+--
+
+print("testoutput from lua")
+local a = Account{balance=100}
+a:withdraw(25.00)
+a:deposit(50.00)
+print("Account balance = $"..a:balance())
+
+local e = Euclid()
+print("Euclid gcd = "..e:gcd(10000,2))
Index: trunk/src/lib/script_engine/luna/luna.h
===================================================================
--- trunk/src/lib/script_engine/luna/luna.h	(revision 8061)
+++ trunk/src/lib/script_engine/luna/luna.h	(revision 8061)
@@ -0,0 +1,130 @@
+/*
+ * Lenny Palozzi - lenny.palozzi@home.com
+ */
+
+#include <string>
+#include <iostream>
+
+#include "luaincl.h"
+
+/*extern "C" {
+#include <lua.h>
+}
+*/
+template <class T>
+class Luna
+{
+
+
+ public:
+   /* member function map */
+   struct RegType {
+      const char* name;
+      int(T::*mfunc)(lua_State*);
+   };
+   /* register class T */
+   static void Register(lua_State* L) {
+      lua_pushcfunction(L, &Luna<T>::constructor);
+      lua_setglobal(L, T::className);
+
+
+     /* if (otag == 0) {
+        otag = lua_newtag(L);
+        lua_pushcfunction(L, &Luna<T>::gc_obj);
+        lua_settagmethod(L, otag, "gc"); /* tm to release objects
+      }*/
+   }
+
+ private:
+   static int otag; /* object tag */
+
+   /* member function dispatcher */
+   static int thunk(lua_State* L) {
+      /* stack = closure(-1), [args...], 'self' table(1) */
+      //int i = static_cast<int>(lua_tonumber(L,-1));
+
+       int i = lua_upvalueindex (1);
+
+      //lua_pushnumber(L, 0); /* userdata object at index 0 */
+      //lua_gettable(L, 1);
+      lua_rawgeti (L, 1, 0);
+      T* obj = (T*)(lua_touserdata(L,-1));
+      lua_pop(L, 1); /* pop closure value and obj */
+
+        printf("FUNCTION:: %d\n", i );
+        printf("OBJECT %p\n", obj);
+
+
+      return (obj->*(T::Register[i].mfunc))(L);
+   }
+
+
+    static int setScriptable(T* obj)
+     {
+     //return registerObject(obj);
+     }
+
+   static int setScriptable(const std::string& objectName)
+    {
+   //#warning 'implement do not use'
+  //   return registerObject(obj);
+    }
+
+   /* constructs T objects */
+   static int constructor(lua_State* L) {
+      T* obj= new T(L); /* new T */
+       printf("OBJECT CREATED %p\n", obj);
+
+      return registerObject(obj, L);
+   }
+
+
+   /* releases objects */
+   static int gc_obj(lua_State* L) {
+      T* obj = static_cast<T*>(lua_touserdata(L, -1));
+      delete obj;
+      return 0;
+   }
+ protected:
+   Luna(); /* hide default constructor */
+
+ private:
+
+   static int registerObject(T* obj, lua_State* L)
+    {
+      lua_newtable(L); /* new table object */
+      //int  objRef = luaL_ref (L, LUA_REGISTRYINDEX);
+
+      //lua_pushnumber(L, 0); /* userdata obj at index 0 */
+      //lua_rawgeti(L, LUA_REGISTRYINDEX, objRef);
+      lua_pushlightuserdata(L, obj);
+      lua_rawseti(L,-2,0);
+      //lua_pushusertag(L, obj, otag); /* have gc call tm */
+      //lua_settable(L, -3);
+      //std::cout<<"test"<<std::endl;
+
+    /* Set up garbage collection
+      if(lua_getmetatable(L, objRef) != 0)
+       {
+        //std::cout<<"test"<<std::endl;
+        lua_pushstring (L, "__gc");
+        lua_pushcfunction(L, &Luna<T>::gc_obj);
+        lua_settable(L,-3);
+       }
+    */
+      //lua_rawgeti (L, LUA_REGISTRYINDEX, objRef);
+      /* register the member functions */
+      for (int i=0; T::Register[i].name; i++)
+      {
+         lua_pushstring(L, T::Register[i].name);
+         lua_pushnumber(L, i);
+         lua_pushcclosure(L, &Luna<T>::thunk, 1);
+         lua_settable(L,-3);
+      }
+      return 1; /* return the table object */
+}
+
+
+};
+template <class T>
+int Luna<T>::otag = 0;
Index: trunk/src/lib/script_engine/lunar.h
===================================================================
--- trunk/src/lib/script_engine/lunar.h	(revision 8061)
+++ trunk/src/lib/script_engine/lunar.h	(revision 8061)
@@ -0,0 +1,244 @@
+#ifndef _LUNAR_H
+#define _LUNAR_H
+
+#include <string>
+#include "Script.h"
+
+#include "luaincl.h"
+
+
+
+    template <typename T> class Lunar {
+      typedef struct { T *pT; } userdataType;
+    public:
+      typedef int (T::*mfp)(lua_State *L);
+      typedef struct { const char *name; mfp mfunc; } RegType;
+
+
+      static void Register(Script* script)
+      {
+        if(script != NULL)
+          Register(script->getLuaState());
+      }
+
+      static void Register(lua_State *L) {
+        lua_newtable(L);
+        int methods = lua_gettop(L);
+
+        luaL_newmetatable(L, T::className);
+        int metatable = lua_gettop(L);
+
+        // store method table in globals so that
+        // scripts can add functions written in Lua.
+        lua_pushvalue(L, methods);
+        set(L, LUA_GLOBALSINDEX, T::className);
+
+        // hide metatable from Lua getmetatable()
+        lua_pushvalue(L, methods);
+        set(L, metatable, "__metatable");
+
+        lua_pushvalue(L, methods);
+        set(L, metatable, "__index");
+
+        lua_pushcfunction(L, tostring_T);
+        set(L, metatable, "__tostring");
+
+        lua_pushcfunction(L, gc_T);
+        set(L, metatable, "__gc");
+
+        lua_newtable(L);                // mt for method table
+        lua_pushcfunction(L, new_T);
+        lua_pushvalue(L, -1);           // dup new_T function
+        set(L, methods, "new");         // add new_T to method table
+        set(L, -3, "__call");           // mt.__call = new_T
+        lua_setmetatable(L, methods);
+
+        // fill method table with methods from class T
+        for (RegType *l = T::methods; l->name; l++) {
+          lua_pushstring(L, l->name);
+          lua_pushlightuserdata(L, (void*)l);
+          lua_pushcclosure(L, thunk, 1);
+          lua_settable(L, methods);
+        }
+
+        lua_pop(L, 2);  // drop metatable and method table
+      }
+
+      // call named lua method from userdata method table
+      static int call(lua_State *L, const char *method,
+                      int nargs=0, int nresults=LUA_MULTRET, int errfunc=0)
+      {
+        int base = lua_gettop(L) - nargs;  // userdata index
+        if (!luaL_checkudata(L, base, T::className)) {
+          lua_settop(L, base-1);           // drop userdata and args
+          lua_pushfstring(L, "not a valid %s userdata", T::className);
+          return -1;
+        }
+
+        lua_pushstring(L, method);         // method name
+        lua_gettable(L, base);             // get method from userdata
+        if (lua_isnil(L, -1)) {            // no method?
+          lua_settop(L, base-1);           // drop userdata and args
+          lua_pushfstring(L, "%s missing method '%s'", T::className, method);
+          return -1;
+        }
+        lua_insert(L, base);               // put method under userdata, args
+
+        int status = lua_pcall(L, 1+nargs, nresults, errfunc);  // call method
+        if (status) {
+          const char *msg = lua_tostring(L, -1);
+          if (msg == NULL) msg = "(error with no message)";
+          lua_pushfstring(L, "%s:%s status = %d\n%s",
+                          T::className, method, status, msg);
+          lua_remove(L, base);             // remove old message
+          return -1;
+        }
+        return lua_gettop(L) - base + 1;   // number of results
+      }
+
+      // push onto the Lua stack a userdata containing a pointer to T object
+      static int push(lua_State *L, T *obj, bool gc=false) {
+        if (!obj) { lua_pushnil(L); return 0; }
+        luaL_getmetatable(L, T::className);  // lookup metatable in Lua registry
+        if (lua_isnil(L, -1)) luaL_error(L, "%s missing metatable", T::className);
+        int mt = lua_gettop(L);
+        subtable(L, mt, "userdata", "v");
+        userdataType *ud =
+          static_cast<userdataType*>(pushuserdata(L, obj, sizeof(userdataType)));
+        if (ud) {
+          ud->pT = obj;  // store pointer to object in userdata
+          lua_pushvalue(L, mt);
+          lua_setmetatable(L, -2);
+          if (gc == false) {
+            lua_checkstack(L, 3);
+            subtable(L, mt, "do not trash", "k");
+            lua_pushvalue(L, -2);
+            lua_pushboolean(L, 1);
+            lua_settable(L, -3);
+            lua_pop(L, 1);
+          }
+        }
+        lua_replace(L, mt);
+        lua_settop(L, mt);
+        return mt;  // index of userdata containing pointer to T object
+      }
+
+
+      static int insertObject(lua_State* L, T* obj, const std::string& name, bool gc=false)
+      {
+        int objectRef = push(L, obj, gc);
+
+        lua_pushlstring(L, name.c_str(), name.size());
+        lua_pushvalue(L, objectRef );
+        lua_settable(L, LUA_GLOBALSINDEX );
+
+        return objectRef;
+      }
+
+
+      static int insertObject(Script* script, T* obj, const std::string& name, bool gc=false)
+      {
+        if(script != NULL)
+          return insertObject(script->getLuaState(), obj, name, gc);
+
+
+      }
+
+      // get userdata from Lua stack and return pointer to T object
+      static T *check(lua_State *L, int narg) {
+        userdataType *ud =
+          static_cast<userdataType*>(luaL_checkudata(L, narg, T::className));
+        if(!ud) luaL_typerror(L, narg, T::className);
+        return ud->pT;  // pointer to T object
+      }
+
+    private:
+      Lunar();  // hide default constructor
+
+      // member function dispatcher
+      static int thunk(lua_State *L) {
+        // stack has userdata, followed by method args
+        T *obj = check(L, 1);  // get 'self', or if you prefer, 'this'
+        lua_remove(L, 1);  // remove self so member function args start at index 1
+        // get member function from upvalue
+        RegType *l = static_cast<RegType*>(lua_touserdata(L, lua_upvalueindex(1)));
+        return (obj->*(l->mfunc))(L);  // call member function
+      }
+
+      // create a new T object and
+      // push onto the Lua stack a userdata containing a pointer to T object
+      static int new_T(lua_State *L) {
+        lua_remove(L, 1);   // use classname:new(), instead of classname.new()
+        T *obj = new T(L);  // call constructor for T objects
+        push(L, obj, true); // gc_T will delete this object
+        return 1;           // userdata containing pointer to T object
+      }
+
+      // garbage collection metamethod
+      static int gc_T(lua_State *L) {
+        if (luaL_getmetafield(L, 1, "do not trash")) {
+          lua_pushvalue(L, 1);  // dup userdata
+          lua_gettable(L, -2);
+          if (!lua_isnil(L, -1)) return 0;  // do not delete object
+        }
+        userdataType *ud = static_cast<userdataType*>(lua_touserdata(L, 1));
+        T *obj = ud->pT;
+        if (obj) delete obj;  // call destructor for T objects
+        return 0;
+      }
+
+      static int tostring_T (lua_State *L) {
+        char buff[32];
+        userdataType *ud = static_cast<userdataType*>(lua_touserdata(L, 1));
+        T *obj = ud->pT;
+        sprintf(buff, "%p", obj);
+        lua_pushfstring(L, "%s (%s)", T::className, buff);
+        return 1;
+      }
+
+      static void set(lua_State *L, int table_index, const char *key) {
+        lua_pushstring(L, key);
+        lua_insert(L, -2);  // swap value and key
+        lua_settable(L, table_index);
+      }
+
+      static void weaktable(lua_State *L, const char *mode) {
+        lua_newtable(L);
+        lua_pushvalue(L, -1);  // table is its own metatable
+        lua_setmetatable(L, -2);
+        lua_pushliteral(L, "__mode");
+        lua_pushstring(L, mode);
+        lua_settable(L, -3);   // metatable.__mode = mode
+      }
+
+      static void subtable(lua_State *L, int tindex, const char *name, const char *mode) {
+        lua_pushstring(L, name);
+        lua_gettable(L, tindex);
+        if (lua_isnil(L, -1)) {
+          lua_pop(L, 1);
+          lua_checkstack(L, 3);
+          weaktable(L, mode);
+          lua_pushstring(L, name);
+          lua_pushvalue(L, -2);
+          lua_settable(L, tindex);
+        }
+      }
+
+      static void *pushuserdata(lua_State *L, void *key, size_t sz) {
+        void *ud = 0;
+        lua_pushlightuserdata(L, key);
+        lua_gettable(L, -2);     // lookup[key]
+        if (lua_isnil(L, -1)) {
+          lua_pop(L, 1);         // drop nil
+          lua_checkstack(L, 3);
+          ud = lua_newuserdata(L, sz);  // create new userdata
+          lua_pushlightuserdata(L, key);
+          lua_pushvalue(L, -2);  // dup userdata
+          lua_settable(L, -4);   // lookup[key] = userdata
+        }
+        return ud;
+      }
+    };
+
+#endif /* _LUNAR_H */
+
Index: trunk/src/lib/script_engine/lunartest.lua
===================================================================
--- trunk/src/lib/script_engine/lunartest.lua	(revision 8061)
+++ trunk/src/lib/script_engine/lunartest.lua	(revision 8061)
@@ -0,0 +1,35 @@
+ function printf(...) io.write(string.format(unpack(arg))) end
+
+function Account:show()
+  printf("Account balance = $%0.02f\n", self:balance())
+end
+
+
+o = Object()
+o:printName()
+
+Obj:printName() --external added object
+
+a = Account(100)
+b = Account:new(30)
+
+print('a =', a)
+print('b =', b)
+print('metatable =', getmetatable(a))
+print('Account =', Account)
+table.foreach(Account, print)
+
+a:show() a:deposit(50.30) a:show() a:withdraw(25.10) a:show()
+
+
+
+parent = {}
+ function parent:rob(amount)
+  amount = amount or self:balance()
+  self:withdraw(amount)
+  return amount
+end
+
+getmetatable(Account).__index = parent
+
+--debug.debug()
Index: trunk/src/lib/script_engine/lunartest2.lua
===================================================================
--- trunk/src/lib/script_engine/lunartest2.lua	(revision 8061)
+++ trunk/src/lib/script_engine/lunartest2.lua	(revision 8061)
@@ -0,0 +1,32 @@
+function printf(...) io.write(string.format(unpack(arg))) end
+
+function Account:show()
+  printf("Account balance = $%0.02f\n", self:balance())
+end
+
+parent = {}
+
+function parent:rob(amount)
+  amount = amount or self:balance()
+  self:withdraw(amount)
+  return amount
+end
+
+getmetatable(Account).__index = parent
+
+function main(arg)
+  io.write("main received ", arg)
+  io.write(" as parameter\n")
+  Obj:printName()
+  print('a =', a)
+  print('b =', b)
+  print('metatable =', getmetatable(a))
+  print('Account =', Account)
+  table.foreach(Account, print)
+
+  a:show() a:deposit(50.30) a:show() a:withdraw(25.10) a:show()
+  Obj:printName()
+
+  return 2
+  --debug.debug()
+end
