Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 7653 in orxonox.OLD for branches/script_engine/src


Ignore:
Timestamp:
May 17, 2006, 7:55:59 PM (19 years ago)
Author:
bensch
Message:

orxonox/script_engine: namespace OrxScript introduced

Location:
branches/script_engine/src/lib/script_engine
Files:
10 edited

Legend:

Unmodified
Added
Removed
  • branches/script_engine/src/lib/script_engine/LuaCallback.h

    r7645 r7653  
    77#include <stdio.h>
    88
    9 class LuaVirtualMachine;
     9namespace OrxScript
     10{
     11  class LuaVirtualMachine;
    1012
    1113
    12 /**
    13  * @brief This function accually executes a method called by Lua.
    14  *
    15  * @param lua Since this function gets called by lua it has to have a lua_State as parameter
    16  *
    17  * @return the number of return values. (which can be found on the stack)
    18  *
    19  * For Lua doesn't know how to handle C++ objects it pushes the Objecttable (including the objectpointer) on top of the stack and
    20  * calls this function.
    21  *
    22  *
    23  * @todo handle an acces to a nonexistent (deleted) object
    24  */
     14  /**
     15   * @brief This function accually executes a method called by Lua.
     16   *
     17   * @param lua Since this function gets called by lua it has to have a lua_State as parameter
     18   *
     19   * @return the number of return values. (which can be found on the stack)
     20   *
     21   * For Lua doesn't know how to handle C++ objects it pushes the Objecttable (including the objectpointer) on top of the stack and
     22   * calls this function.
     23   *
     24   *
     25   * @todo handle an acces to a nonexistent (deleted) object
     26   */
    2527
    2628
    27 static int luaCallback (lua_State *lua)
    28 {
     29  static int luaCallback (lua_State *lua)
     30  {
    2931
    30  // Locate the psudo-index for the function number
    31   int methodNumber = lua_upvalueindex (1);
    32   int returnCount = 0;
     32    // Locate the psudo-index for the function number
     33    int methodNumber = lua_upvalueindex (1);
     34    int returnCount = 0;
    3335
    34   bool functionSuccess = false;
     36    bool functionSuccess = false;
    3537
    36  // Check for the "this" table
    37   if (lua_istable (lua, 1))
    38   {
    39    // Found the "this" table. The object pointer is at the index 0
    40     lua_rawgeti (lua, 1, 0);
     38    // Check for the "this" table
     39    if (lua_istable (lua, 1))
     40    {
     41      // Found the "this" table. The object pointer is at the index 0
     42      lua_rawgeti (lua, 1, 0);
    4143
    42     if (lua_islightuserdata (lua, -1))
     44      if (lua_islightuserdata (lua, -1))
     45      {
     46        // Found the pointer, need to cast it
     47        Scriptable* thisPointer = (Scriptable*) lua_touserdata (lua, -1);
     48
     49        // Get the method index
     50        int methodIndex = (int) lua_tonumber (lua, methodNumber);
     51
     52        // Reformat the stack so our parameters are correct
     53        // Clean up the "this" table
     54        lua_remove (lua, 1);
     55        // Clean up the thisPointer pointer
     56        lua_remove (lua, -1);
     57
     58        //debug
     59        //std::cout<<thisPointer->whatIsThis()<<std::endl;
     60
     61        LuaScript* originScript = NULL;
     62
     63        lua_getglobal (lua, "this");
     64
     65        if (lua_istable (lua, 1))
     66        {
     67          // Found the "this" table. The object pointer is at the index 0
     68          lua_rawgeti (lua, 1, 0);
     69
     70          if (lua_islightuserdata (lua, -1))
     71          {
     72            // Found the pointer, need to cast it
     73            originScript = (LuaScript *) lua_touserdata (lua, -1);
     74          }
     75        }
     76
     77        if(originScript == NULL)
     78        {//do something usefull
     79        }
     80        //debug
     81        // std::cout<<originScript->whatIsThis()<<std::endl;
     82
     83        LuaVirtualMachine virtualMachine = originScript->getVirtualMachine();
     84        //debug
     85        //std::cout<<"test "<< thisPointer->methods(virtualMachine)<<std::endl;
     86        // Check that the method is correct index
     87        assert ((methodIndex <= thisPointer->methods(virtualMachine) ));
     88        // Call the class
     89        returnCount = thisPointer->scriptCalling ( virtualMachine, thisPointer->getFunctionAtIndex(methodIndex,virtualMachine));
     90
     91        functionSuccess = true;
     92      }
     93    }
     94
     95    if (functionSuccess == false)
    4396    {
    44      // Found the pointer, need to cast it
    45       Scriptable* thisPointer = (Scriptable*) lua_touserdata (lua, -1);
     97      lua_pushstring (lua, "luaCallback -> Failed to call the class function");
     98      lua_error (lua);
     99    }
    46100
    47       // Get the method index
    48       int methodIndex = (int) lua_tonumber (lua, methodNumber);
    49 
    50      // Reformat the stack so our parameters are correct
    51      // Clean up the "this" table
    52       lua_remove (lua, 1);
    53      // Clean up the thisPointer pointer
    54       lua_remove (lua, -1);
    55 
    56       //debug
    57       //std::cout<<thisPointer->whatIsThis()<<std::endl;
    58 
    59       LuaScript* originScript = NULL;
    60 
    61       lua_getglobal (lua, "this");
    62 
    63       if (lua_istable (lua, 1))
    64       {
    65    // Found the "this" table. The object pointer is at the index 0
    66         lua_rawgeti (lua, 1, 0);
    67 
    68         if (lua_islightuserdata (lua, -1))
    69         {
    70      // Found the pointer, need to cast it
    71            originScript = (LuaScript *) lua_touserdata (lua, -1);
    72         }
    73       }
    74 
    75       if(originScript == NULL)
    76       {//do something usefull
    77       }
    78       //debug
    79      // std::cout<<originScript->whatIsThis()<<std::endl;
    80 
    81       LuaVirtualMachine virtualMachine = originScript->getVirtualMachine();
    82       //debug
    83       //std::cout<<"test "<< thisPointer->methods(virtualMachine)<<std::endl;
    84       // Check that the method is correct index
    85       assert ((methodIndex <= thisPointer->methods(virtualMachine) ));
    86       // Call the class
    87       returnCount = thisPointer->scriptCalling ( virtualMachine, thisPointer->getFunctionAtIndex(methodIndex,virtualMachine));
    88 
    89       functionSuccess = true;
    90     }
     101    // Number of return variables
     102    return returnCount;
    91103  }
    92 
    93   if (functionSuccess == false)
    94   {
    95     lua_pushstring (lua, "luaCallback -> Failed to call the class function");
    96     lua_error (lua);
    97   }
    98 
    99    // Number of return variables
    100   return returnCount;
    101104}
    102 
    103105#endif /* __LUA_CALLBACK_H__*/
  • branches/script_engine/src/lib/script_engine/RestoreStack.h

    r7645 r7653  
    44#include "luaincl.h"
    55
    6 //! Class to restore the stack to the way we found it.
    7 class LuaRestoreStack
     6namespace OrxScript
    87{
    9 public:
    10   /**
    11    * @brief Stores the stack and the index to the top element
    12    *
    13    * @param virtualMachine the virtual machine to save
    14    */
    15    LuaRestoreStack (LuaVirtualMachine& virtualMachine) : savedState (NULL)
    16    {
     8
     9  //! Class to restore the stack to the way we found it.
     10  class LuaRestoreStack
     11  {
     12  public:
     13    /**
     14     * @brief Stores the stack and the index to the top element
     15     *
     16     * @param virtualMachine the virtual machine to save
     17     */
     18    LuaRestoreStack (LuaVirtualMachine& virtualMachine) : savedState (NULL)
     19    {
    1720      savedState = (lua_State *) virtualMachine;
    1821      if (virtualMachine.isOk ())
    1922      {
    20          savedTopIndex = lua_gettop (savedState);
     23        savedTopIndex = lua_gettop (savedState);
    2124      }
    22    }
    23    /**
    24     * @brief Restores the virtual machine
    25     *
    26     *
    27     */
    28    virtual ~LuaRestoreStack (void)
    29    {
     25    }
     26    /**
     27     * @brief Restores the virtual machine
     28     *
     29     *
     30     */
     31    virtual ~LuaRestoreStack (void)
     32    {
    3033      lua_settop (savedState, savedTopIndex);
    31    }
     34    }
    3235
    33 protected:
    34    lua_State* savedState;
    35    int savedTopIndex;
    36 };
     36  protected:
     37    lua_State* savedState;
     38    int savedTopIndex;
     39  };
    3740
     41}
    3842
    3943#endif // __RESTORE_STACK_H__
  • branches/script_engine/src/lib/script_engine/Script.cc

    r7645 r7653  
    99// ---------------------------------------------------------------------------
    1010
     11namespace OrxScript
     12{
     13
    1114#define BEGIN_LUA_CHECK(vm)   lua_State *state = (lua_State *) vm; \
    1215                              if (vm.isOk ()) {
     
    1417
    1518
    16 /**
    17  * @brief Constructor. Sets up the lua stack and the "this" table
    18  *
    19  *
    20  *
    21  */
    22 
    23 LuaScript::LuaScript ()
    24   : methodCount (0) , argumentCount (0), functionName()
    25 {
    26   virtualMachine.init();
    27   lua_State *state = (lua_State *) virtualMachine;
    28 
    29  if (virtualMachine.isOk ()) {
     19  /**
     20   * @brief Constructor. Sets up the lua stack and the "this" table
     21   *
     22   *
     23   *
     24   */
     25
     26  LuaScript::LuaScript ()
     27      : methodCount (0) , argumentCount (0), functionName()
     28  {
     29    virtualMachine.init();
     30    lua_State *state = (lua_State *) virtualMachine;
     31
     32    if (virtualMachine.isOk ())
     33    {
    3034      // Create a reference to the "this" table. Each reference is unique
    31   lua_newtable (state);
    32   thisReference = luaL_ref (state, LUA_REGISTRYINDEX);
     35      lua_newtable (state);
     36      thisReference = luaL_ref (state, LUA_REGISTRYINDEX);
    3337
    3438      // Save the "this" table to index 0 of the "this" table
    35   LuaRestoreStack rs (virtualMachine);
    36   lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
    37   lua_pushlightuserdata (state, (void *) this);
    38   lua_rawseti (state, -2, 0);
    39 }
    40 
    41 }
    42 
    43 
    44 /**
    45  * @brief Deconstructor
    46  *
    47  */
    48 
    49 LuaScript::~LuaScript (void)
    50 {
    51   LuaRestoreStack rs (virtualMachine);
    52 
    53   BEGIN_LUA_CHECK (virtualMachine)
    54   // Get the reference "this" table
    55   lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
    56 
    57       // Clear index 0
    58   lua_pushnil (state);
    59   lua_rawseti (state, -2, 0);
    60   END_LUA_CHECK
    61 
    62 }
    63 
    64 
    65 
    66 /**
    67  * @brief Compiles a given buffer. (reads it into the lua stack)
    68  * @param pbBuffer buffer to compile
    69  * @param size_t length of the buffer
    70  *
    71  * @return true if it succeeded
    72  */
    73 
    74 bool LuaScript::compileBuffer (unsigned char *pbBuffer, size_t szLen)
    75 {
    76   assert (pbBuffer != NULL && "LuaScript::compileBuffer ->  pbBuffer == NULL");
    77   assert (szLen != 0 && "LuaScript::compileBuffer -> szLen == 0");
    78   assert (virtualMachine.isOk () && "VM Not OK");
    79 
    80    // Make sure we have the correct "this" table
    81   LuaThis luaThis (virtualMachine, thisReference);
    82 
    83   return virtualMachine.runBuffer (pbBuffer, szLen);
    84 }
    85 
    86 
    87 /**
    88  * @brief Compiles a given file. (reads it into the lua stack)
    89  * @param strFilename filename
    90  *
    91  * @return true if it succeeded
    92  */
    93 
    94 bool LuaScript::compileFile (const std::string& strFilename)
    95 {
    96   //assert (strFilename != NULL && "LuaScript::compileFile -> strFilename == NULL");
    97   assert (virtualMachine.isOk () && "VM Not OK");
    98 
    99    // Make sure we have the correct "this" table
    100   LuaThis luaThis (virtualMachine, thisReference);
    101 
    102   return virtualMachine.runFile (strFilename);
    103 }
    104 
    105 
    106 /**
    107  * @brief Registers a function with Lua, the function will be registered in the "this" table
    108  * @param strFuncName name of the function by which it goes by in lua
    109  *
    110  * @return the pseudoindex of the function
    111  */
    112 
    113 int LuaScript::registerFunction (const std::string& strFuncName)
    114 {
    115 //  assert (strFuncName != NULL && "LuaScript::registerFunction -> strFuncName == NULL");
    116   assert (virtualMachine.isOk () && "VM Not OK");
    117 
    118   int iMethodIdx = -1;
    119 
    120   LuaRestoreStack rs (virtualMachine);
    121 
    122   BEGIN_LUA_CHECK (virtualMachine)
    123       iMethodIdx = ++methodCount;
    124 
    125       // Register a function with the lua script. Added it to the "this" table
    126   lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
    127 
    128       // Push the function and parameters
    129   lua_pushstring (state, strFuncName.c_str());
    130   lua_pushnumber (state, (lua_Number) iMethodIdx);
    131   lua_pushcclosure (state, luaCallback, 1);
    132   lua_settable (state, -3);
    133 
    134   END_LUA_CHECK
    135 
    136       return iMethodIdx;
    137 }
    138 
    139 
    140 /**
    141  * @brief Selects a script function to run
    142  * @param  strFuncName name of the function to run
    143  *
    144  * @return true on success
    145  */
    146 bool LuaScript::selectScriptFunction (const std::string& strFuncName)
    147 {
    148 //  assert (strFuncName != NULL && "LuaScript::selectScriptFunction -> strFuncName == NULL");
    149   assert (virtualMachine.isOk () && "VM Not OK");
    150 
    151   bool fSuccess = true;
    152 
    153   BEGIN_LUA_CHECK (virtualMachine)
    154   // Look up function name
    155   lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
    156   lua_pushstring (state, strFuncName.c_str());
    157   lua_rawget (state, -2);
    158   lua_remove (state, -2);
    159 
    160       // Put the "this" table back
    161   lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
    162 
    163       // Check that we have a valid function
    164   if (!lua_isfunction (state, -2))
    165   {
    166     fSuccess = false;
    167     lua_pop (state, 2);
    168   }
    169   else
    170   {
    171     argumentCount = 0;
    172     functionName = strFuncName;
    173   }
    174   END_LUA_CHECK
    175 
    176       return fSuccess;
    177 }
    178 
    179 
    180 /**
    181  * @brief Checks to see if a function exists
    182  * @param  functionName  Function name
    183  *
    184  * @return true if the function exists
    185  */
    186 bool LuaScript::scriptHasFunction (const std::string& functionName)
    187 {
    188   // printf("entered scriptHasFunction\n");
    189 
    190 //  assert (strScriptName != NULL && "LuaScript::scriptHasFunction -> strScriptName == NULL");
    191   assert (virtualMachine.isOk () && "VM Not OK");
    192 
    193 // printf("assertions passed\n");
    194 
    195   LuaRestoreStack rs (virtualMachine);
    196 
    197   bool fFoundFunc = false;
    198 
    199   BEGIN_LUA_CHECK (virtualMachine)
    200   lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
    201   lua_pushstring (state, functionName.c_str());
    202   lua_rawget (state, -2);
    203   lua_remove (state, -2);
    204 
    205   if (lua_isfunction (state, -1))
    206   {
    207     fFoundFunc = true;
    208   }
    209   END_LUA_CHECK
    210 
    211       return fFoundFunc;
    212 
    213 }
    214 
    215 
    216 /**
    217  * @brief Adds a parameter to the parameter list
    218  * @param  string  string to be added as parameter for a function.
    219  *
    220  */
    221 
    222 void LuaScript::addParam (char *string)
    223 {
    224   assert (string != NULL && "LuaScript::addParam -> string == NULL");
    225   assert (virtualMachine.isOk () && "VM Not OK");
    226 
    227   BEGIN_LUA_CHECK (virtualMachine)
    228       lua_pushstring (state, string);
    229   ++argumentCount;
    230   END_LUA_CHECK
    231 }
    232 
    233 
    234 /**
    235  * @brief Adds a parameter to the parameter list
    236  * @param  iInt  integer to be added as parameter for a function.
    237  *
    238  */
    239 
    240 void LuaScript::addParam (int iInt)
    241 {
    242   assert (virtualMachine.isOk () && "VM Not OK");
    243 
    244   BEGIN_LUA_CHECK (virtualMachine)
    245       lua_pushnumber (state, (lua_Number) iInt);
    246   ++argumentCount;
    247   END_LUA_CHECK
    248 }
    249 
    250 
    251 /**
    252  * @brief Adds a parameter to the parameter list
    253  * @param  fFloat  float to be added as parameter for a function.
    254  *
    255  */
    256 void LuaScript::addParam (float fFloat)
    257 {
    258   assert (virtualMachine.isOk () && "VM Not OK");
    259 
    260   BEGIN_LUA_CHECK (virtualMachine)
    261       lua_pushnumber (state, (lua_Number) fFloat);
    262   ++argumentCount;
    263   END_LUA_CHECK
    264 }
    265 
    266 
    267 /**
    268  * @brief Runs the selected script function
    269  * @param  nReturns the count of return values
    270  *
    271  * @return true on success
    272  */
    273 bool LuaScript::run (int nReturns /* = 0 */)
    274 {
    275   assert (virtualMachine.isOk () && "VM Not OK");
    276 
    277    // At this point there should be a parameters and a function on the
    278    // Lua stack. Each function get a "this" parameter as default and is
    279    // pushed onto the stack when the method is selected
    280 
    281   bool fSuccess = virtualMachine.callFunction (argumentCount + 1, nReturns);
    282 
    283   if (fSuccess == true && nReturns > 0)
    284   {
     39      LuaRestoreStack rs (virtualMachine);
     40      lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
     41      lua_pushlightuserdata (state, (void *) this);
     42      lua_rawseti (state, -2, 0);
     43    }
     44
     45  }
     46
     47
     48  /**
     49   * @brief Deconstructor
     50   *
     51   */
     52
     53  LuaScript::~LuaScript (void)
     54  {
     55    LuaRestoreStack rs (virtualMachine);
     56
     57    BEGIN_LUA_CHECK (virtualMachine)
     58    // Get the reference "this" table
     59    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
     60
     61    // Clear index 0
     62    lua_pushnil (state);
     63    lua_rawseti (state, -2, 0);
     64    END_LUA_CHECK
     65
     66  }
     67
     68
     69
     70  /**
     71   * @brief Compiles a given buffer. (reads it into the lua stack)
     72   * @param pbBuffer buffer to compile
     73   * @param size_t length of the buffer
     74   *
     75   * @return true if it succeeded
     76   */
     77
     78  bool LuaScript::compileBuffer (unsigned char *pbBuffer, size_t szLen)
     79  {
     80    assert (pbBuffer != NULL && "LuaScript::compileBuffer ->  pbBuffer == NULL");
     81    assert (szLen != 0 && "LuaScript::compileBuffer -> szLen == 0");
     82    assert (virtualMachine.isOk () && "VM Not OK");
     83
     84    // Make sure we have the correct "this" table
     85    LuaThis luaThis (virtualMachine, thisReference);
     86
     87    return virtualMachine.runBuffer (pbBuffer, szLen);
     88  }
     89
     90
     91  /**
     92   * @brief Compiles a given file. (reads it into the lua stack)
     93   * @param strFilename filename
     94   *
     95   * @return true if it succeeded
     96   */
     97
     98  bool LuaScript::compileFile (const std::string& strFilename)
     99  {
     100    //assert (strFilename != NULL && "LuaScript::compileFile -> strFilename == NULL");
     101    assert (virtualMachine.isOk () && "VM Not OK");
     102
     103    // Make sure we have the correct "this" table
     104    LuaThis luaThis (virtualMachine, thisReference);
     105
     106    return virtualMachine.runFile (strFilename);
     107  }
     108
     109
     110  /**
     111   * @brief Registers a function with Lua, the function will be registered in the "this" table
     112   * @param strFuncName name of the function by which it goes by in lua
     113   *
     114   * @return the pseudoindex of the function
     115   */
     116
     117  int LuaScript::registerFunction (const std::string& strFuncName)
     118  {
     119    //  assert (strFuncName != NULL && "LuaScript::registerFunction -> strFuncName == NULL");
     120    assert (virtualMachine.isOk () && "VM Not OK");
     121
     122    int iMethodIdx = -1;
     123
     124    LuaRestoreStack rs (virtualMachine);
     125
     126    BEGIN_LUA_CHECK (virtualMachine)
     127    iMethodIdx = ++methodCount;
     128
     129    // Register a function with the lua script. Added it to the "this" table
     130    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
     131
     132    // Push the function and parameters
     133    lua_pushstring (state, strFuncName.c_str());
     134    lua_pushnumber (state, (lua_Number) iMethodIdx);
     135    lua_pushcclosure (state, luaCallback, 1);
     136    lua_settable (state, -3);
     137
     138    END_LUA_CHECK
     139
     140    return iMethodIdx;
     141  }
     142
     143
     144  /**
     145   * @brief Selects a script function to run
     146   * @param  strFuncName name of the function to run
     147   *
     148   * @return true on success
     149   */
     150  bool LuaScript::selectScriptFunction (const std::string& strFuncName)
     151  {
     152    //  assert (strFuncName != NULL && "LuaScript::selectScriptFunction -> strFuncName == NULL");
     153    assert (virtualMachine.isOk () && "VM Not OK");
     154
     155    bool fSuccess = true;
     156
     157    BEGIN_LUA_CHECK (virtualMachine)
     158    // Look up function name
     159    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
     160    lua_pushstring (state, strFuncName.c_str());
     161    lua_rawget (state, -2);
     162    lua_remove (state, -2);
     163
     164    // Put the "this" table back
     165    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
     166
     167    // Check that we have a valid function
     168    if (!lua_isfunction (state, -2))
     169    {
     170      fSuccess = false;
     171      lua_pop (state, 2);
     172    }
     173    else
     174    {
     175      argumentCount = 0;
     176      functionName = strFuncName;
     177    }
     178    END_LUA_CHECK
     179
     180    return fSuccess;
     181  }
     182
     183
     184  /**
     185   * @brief Checks to see if a function exists
     186   * @param  functionName  Function name
     187   *
     188   * @return true if the function exists
     189   */
     190  bool LuaScript::scriptHasFunction (const std::string& functionName)
     191  {
     192    // printf("entered scriptHasFunction\n");
     193
     194    //  assert (strScriptName != NULL && "LuaScript::scriptHasFunction -> strScriptName == NULL");
     195    assert (virtualMachine.isOk () && "VM Not OK");
     196
     197    // printf("assertions passed\n");
     198
     199    LuaRestoreStack rs (virtualMachine);
     200
     201    bool fFoundFunc = false;
     202
     203    BEGIN_LUA_CHECK (virtualMachine)
     204    lua_rawgeti (state, LUA_REGISTRYINDEX, thisReference);
     205    lua_pushstring (state, functionName.c_str());
     206    lua_rawget (state, -2);
     207    lua_remove (state, -2);
     208
     209    if (lua_isfunction (state, -1))
     210    {
     211      fFoundFunc = true;
     212    }
     213    END_LUA_CHECK
     214
     215    return fFoundFunc;
     216
     217  }
     218
     219
     220  /**
     221   * @brief Adds a parameter to the parameter list
     222   * @param  string  string to be added as parameter for a function.
     223   *
     224   */
     225
     226  void LuaScript::addParam (char *string)
     227  {
     228    assert (string != NULL && "LuaScript::addParam -> string == NULL");
     229    assert (virtualMachine.isOk () && "VM Not OK");
     230
     231    BEGIN_LUA_CHECK (virtualMachine)
     232    lua_pushstring (state, string);
     233    ++argumentCount;
     234    END_LUA_CHECK
     235  }
     236
     237
     238  /**
     239   * @brief Adds a parameter to the parameter list
     240   * @param  iInt  integer to be added as parameter for a function.
     241   *
     242   */
     243
     244  void LuaScript::addParam (int iInt)
     245  {
     246    assert (virtualMachine.isOk () && "VM Not OK");
     247
     248    BEGIN_LUA_CHECK (virtualMachine)
     249    lua_pushnumber (state, (lua_Number) iInt);
     250    ++argumentCount;
     251    END_LUA_CHECK
     252  }
     253
     254
     255  /**
     256   * @brief Adds a parameter to the parameter list
     257   * @param  fFloat  float to be added as parameter for a function.
     258   *
     259   */
     260  void LuaScript::addParam (float fFloat)
     261  {
     262    assert (virtualMachine.isOk () && "VM Not OK");
     263
     264    BEGIN_LUA_CHECK (virtualMachine)
     265    lua_pushnumber (state, (lua_Number) fFloat);
     266    ++argumentCount;
     267    END_LUA_CHECK
     268  }
     269
     270
     271  /**
     272   * @brief Runs the selected script function
     273   * @param  nReturns the count of return values
     274   *
     275   * @return true on success
     276   */
     277  bool LuaScript::run (int nReturns /* = 0 */)
     278  {
     279    assert (virtualMachine.isOk () && "VM Not OK");
     280
     281    // At this point there should be a parameters and a function on the
     282    // Lua stack. Each function get a "this" parameter as default and is
     283    // pushed onto the stack when the method is selected
     284
     285    bool fSuccess = virtualMachine.callFunction (argumentCount + 1, nReturns);
     286
     287    if (fSuccess == true && nReturns > 0)
     288    {
    285289      // Check for returns
    286     handleReturns (virtualMachine, functionName);
    287     lua_pop ((lua_State *) virtualMachine, nReturns);
    288   }
    289 
    290   return fSuccess;
    291 }
    292 
    293 
    294 /**
    295  * @brief This function adds an object to a script so that the object is accessable from within the luascript.
    296  *
    297  * @param scriptable the scriptable object to add.
    298  * @param strObjName the name that the object goes by in the script.
    299  * @param luaScript  the script to which the scrtiptable is added
    300  *
    301  * @return a lua reference to the added object
    302  *
    303  *
    304  *
    305  */
    306 
    307 int LuaScript::addScriptableToScript(Scriptable* scriptable, const std::string& strObjName)
    308 {
    309 
    310   lua_State *state = (lua_State *) (this->virtualMachine);
    311 
    312   if(strObjName.compare(std::string("this")) != 0)
    313    {
    314   if (virtualMachine.isOk ())
    315     {
    316     /*create object table*/
    317       // Create a reference to the "object" table and set a name for the reference. Each reference is unique
    318 
    319      lua_newtable (state);
    320      int  objRef = luaL_ref (state, LUA_REGISTRYINDEX);
    321      lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
    322      lua_setglobal (state, strObjName.c_str());
    323 
    324 
    325       // Save the "object" table to index 0 of the "object" table
    326      LuaRestoreStack rs(virtualMachine);
    327      lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
    328      lua_pushlightuserdata (state, scriptable);
    329      lua_rawseti (state, -2, 0);
    330 
    331      if(! addScriptableToList(scriptable,objRef))
    332        std::cout<<"scriptable not added"<<std::endl;
    333      if(!(scriptable->scriptableAdded(this,thisReference,objRef)))
    334        std::cout<<"scriptableAdded returned false"<<std::endl;
    335 
    336      return objRef;
    337     }
    338    }
    339 
    340    return -1;
    341 
    342 }
    343 
    344 
    345 
    346 /**
    347  * @brief Add the function to a scriptable in the Script
    348  * @param strFuncName name of the function by which it goes by in lua
    349  * @param toScriptable reference to the scriptable the function should be associated with
    350  * @param methodIndex index of the last function.
    351  *
    352  * @return the pseudoindex of the function, -1 on failure
    353  */
    354 
    355 int LuaScript::addFunctionToScriptable(const std::string& strFuncName, int toScriptable, int lastMethodIndex)
    356 {
    357 //  assert (strFuncName != NULL && "LuaScript::registerFunction -> strFuncName == NULL");
    358   assert (virtualMachine.isOk () && "VM Not OK");
    359 
    360 
    361   //get the last method index from the Script
    362   Scriptable* scriptable = getScriptableByReference(toScriptable);
    363   int iMethodIdx = -1;
    364 
    365   if(scriptable)
    366   {
    367      LuaRestoreStack rs (virtualMachine);
    368 
    369      BEGIN_LUA_CHECK (virtualMachine)
    370     // Register a function with the lua script. Added it to the "toScrtiptable" table
    371      lua_rawgeti (state, LUA_REGISTRYINDEX, toScriptable);
    372 
    373      if (lua_istable (state, 1))
    374      {
    375        iMethodIdx = ++lastMethodIndex;
    376 
    377     // Push the function and parameters
    378        lua_pushstring (state, strFuncName.c_str());
    379        lua_pushnumber (state, (lua_Number) iMethodIdx);
    380        lua_pushcclosure (state, luaCallback, 1);
    381        lua_settable (state, -3);
    382      }
    383      END_LUA_CHECK
    384 
    385   }
    386       return iMethodIdx;
    387 }
    388 
    389 
    390 Scriptable* LuaScript::getScriptableByReference(int scrptblRef)
    391 {
    392 
    393      bool notFound = true;
     290      handleReturns (virtualMachine, functionName);
     291      lua_pop ((lua_State *) virtualMachine, nReturns);
     292    }
     293
     294    return fSuccess;
     295  }
     296
     297
     298  /**
     299   * @brief This function adds an object to a script so that the object is accessable from within the luascript.
     300   *
     301   * @param scriptable the scriptable object to add.
     302   * @param strObjName the name that the object goes by in the script.
     303   * @param luaScript  the script to which the scrtiptable is added
     304   *
     305   * @return a lua reference to the added object
     306   *
     307   *
     308   *
     309   */
     310
     311  int LuaScript::addScriptableToScript(Scriptable* scriptable, const std::string& strObjName)
     312  {
     313
     314    lua_State *state = (lua_State *) (this->virtualMachine);
     315
     316    if(strObjName.compare(std::string("this")) != 0)
     317    {
     318      if (virtualMachine.isOk ())
     319      {
     320        /*create object table*/
     321        // Create a reference to the "object" table and set a name for the reference. Each reference is unique
     322
     323        lua_newtable (state);
     324        int  objRef = luaL_ref (state, LUA_REGISTRYINDEX);
     325        lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
     326        lua_setglobal (state, strObjName.c_str());
     327
     328
     329        // Save the "object" table to index 0 of the "object" table
     330        LuaRestoreStack rs(virtualMachine);
     331        lua_rawgeti (state, LUA_REGISTRYINDEX, objRef);
     332        lua_pushlightuserdata (state, scriptable);
     333        lua_rawseti (state, -2, 0);
     334
     335        if(! addScriptableToList(scriptable,objRef))
     336          std::cout<<"scriptable not added"<<std::endl;
     337        if(!(scriptable->scriptableAdded(this,thisReference,objRef)))
     338          std::cout<<"scriptableAdded returned false"<<std::endl;
     339
     340        return objRef;
     341      }
     342    }
     343
     344    return -1;
     345
     346  }
     347
     348
     349
     350  /**
     351   * @brief Add the function to a scriptable in the Script
     352   * @param strFuncName name of the function by which it goes by in lua
     353   * @param toScriptable reference to the scriptable the function should be associated with
     354   * @param methodIndex index of the last function.
     355   *
     356   * @return the pseudoindex of the function, -1 on failure
     357   */
     358
     359  int LuaScript::addFunctionToScriptable(const std::string& strFuncName, int toScriptable, int lastMethodIndex)
     360  {
     361    //  assert (strFuncName != NULL && "LuaScript::registerFunction -> strFuncName == NULL");
     362    assert (virtualMachine.isOk () && "VM Not OK");
     363
     364
     365    //get the last method index from the Script
     366    Scriptable* scriptable = getScriptableByReference(toScriptable);
     367    int iMethodIdx = -1;
     368
     369    if(scriptable)
     370    {
     371      LuaRestoreStack rs (virtualMachine);
     372
     373      BEGIN_LUA_CHECK (virtualMachine)
     374      // Register a function with the lua script. Added it to the "toScrtiptable" table
     375      lua_rawgeti (state, LUA_REGISTRYINDEX, toScriptable);
     376
     377      if (lua_istable (state, 1))
     378      {
     379        iMethodIdx = ++lastMethodIndex;
     380
     381        // Push the function and parameters
     382        lua_pushstring (state, strFuncName.c_str());
     383        lua_pushnumber (state, (lua_Number) iMethodIdx);
     384        lua_pushcclosure (state, luaCallback, 1);
     385        lua_settable (state, -3);
     386      }
     387      END_LUA_CHECK
     388
     389    }
     390    return iMethodIdx;
     391  }
     392
     393
     394  Scriptable* LuaScript::getScriptableByReference(int scrptblRef)
     395  {
     396
     397    bool notFound = true;
    394398    std::list<Scrptbl>::iterator it = scriptableList.begin();
    395399
     
    406410
    407411    if(notFound)
    408      return NULL;
    409 
    410 }
    411 
    412 int LuaScript::getReferenceByScriptable(Scriptable* scrptbl)
    413 {
    414   bool notFound = true;
     412      return NULL;
     413
     414  }
     415
     416  int LuaScript::getReferenceByScriptable(Scriptable* scrptbl)
     417  {
     418    bool notFound = true;
    415419
    416420    std::list<Scrptbl>::iterator it = scriptableList.begin();
     
    424428      }
    425429      it++;
    426      }
    427   if(notFound)
    428     return -1;
     430    }
     431    if(notFound)
     432      return -1;
     433  }
     434
     435  bool LuaScript::addScriptableToList(Scriptable* scrptbl, int scriptableRef)
     436  {
     437    if(scrptbl)
     438    {
     439      if(getReferenceByScriptable(scrptbl) == -1) // Script isn't there yet
     440      {
     441        Scrptbl scriptableTmp;
     442        scriptableTmp.scriptable = scrptbl;
     443        scriptableTmp.scriptableRef = scriptableRef;
     444        scriptableList.push_back(scriptableTmp);
     445        return true;
     446      }
     447    }
     448
     449    return false;
     450
     451  }
     452
     453  bool LuaScript::removeScriptableFromList(Scriptable* toRemove)
     454  {
     455    if(toRemove)
     456    {
     457      int scrptbl = getReferenceByScriptable(toRemove);
     458
     459      if(scrptbl != -1)// if the scriptable is on the list
     460      {
     461        std::list<Scrptbl>::iterator it = scriptableList.begin();
     462
     463        while((*it).scriptable != toRemove && it != scriptableList.end() )
     464        {
     465          it++;
     466        }
     467
     468        if(it != scriptableList.end())
     469        {
     470          scriptableList.erase(it);
     471          return true;
     472        }
     473      }
     474    }
     475    return false;
     476  }
     477
     478  bool LuaScript::removeScriptableFromList(int scriptable)
     479  {
     480    return removeScriptableFromList(getScriptableByReference(scriptable));
     481  }
     482
     483
     484  char LuaScript::whatIsThis()
     485  {
     486    char result = 'l';
     487    return result;
     488  }
    429489}
    430490
    431 bool LuaScript::addScriptableToList(Scriptable* scrptbl, int scriptableRef)
    432 {
    433   if(scrptbl)
    434   {
    435     if(getReferenceByScriptable(scrptbl) == -1) // Script isn't there yet
    436     {
    437       Scrptbl scriptableTmp;
    438       scriptableTmp.scriptable = scrptbl;
    439       scriptableTmp.scriptableRef = scriptableRef;
    440       scriptableList.push_back(scriptableTmp);
    441       return true;
    442     }
    443   }
    444 
    445   return false;
    446 
    447 }
    448 
    449 bool LuaScript::removeScriptableFromList(Scriptable* toRemove)
    450 {
    451   if(toRemove)
    452   {
    453     int scrptbl = getReferenceByScriptable(toRemove);
    454 
    455     if(scrptbl != -1)// if the scriptable is on the list
    456     {
    457       std::list<Scrptbl>::iterator it = scriptableList.begin();
    458 
    459       while((*it).scriptable != toRemove && it != scriptableList.end() )
    460       {
    461         it++;
    462       }
    463 
    464       if(it != scriptableList.end())
    465       {
    466         scriptableList.erase(it);
    467         return true;
    468       }
    469     }
    470   }
    471   return false;
    472 }
    473 
    474 bool LuaScript::removeScriptableFromList(int scriptable)
    475 {
    476   return removeScriptableFromList(getScriptableByReference(scriptable));
    477 }
    478 
    479 
    480 char LuaScript::whatIsThis()
    481 {
    482   char result = 'l';
    483   return result;
    484 }
    485 
  • branches/script_engine/src/lib/script_engine/Script.h

    r7645 r7653  
    88#include "scriptable.h"
    99
     10namespace OrxScript
     11{
    1012
    11 struct Scrptbl
    12 {
    13   Scriptable* scriptable;
    14   int scriptableRef;
    15 };
     13  struct Scrptbl
     14  {
     15    Scriptable* scriptable;
     16    int scriptableRef;
     17  };
    1618
    17 class LuaScript
    18 {
     19  class LuaScript
     20  {
    1921  public:
    2022    LuaScript ();
     
    2628    /* ------------------ Script related Functions ------------------ */
    2729
    28    // Compile script into Virtual Machine
     30    // Compile script into Virtual Machine
    2931    bool compileFile (const std::string& strFilename);
    3032    bool compileBuffer (unsigned char *pbBuffer, size_t szLen);
    3133
    32    // Register function with Lua in the this table
     34    // Register function with Lua in the this table
    3335    int registerFunction (const std::string& strFuncName);
    3436
    3537
    36    // Selects a Lua Script function to call
     38    // Selects a Lua Script function to call
    3739    bool selectScriptFunction (const std::string& strFuncName);
    3840    void addParam (int iInt);
     
    4042    void addParam (char *string);
    4143
    42    // Runs the loaded script
     44    // Runs the loaded script
    4345    bool run (int nReturns = 0);
    4446
    45    // Checks on Virtual Machine script
     47    // Checks on Virtual Machine script
    4648    bool scriptHasFunction (const std::string& strScriptName);
    4749
    48    // Method indexing check
     50    // Method indexing check
    4951    int methods (void) { return methodCount; }
    5052
    5153
    52    // When the script calls a class method, this is called
     54    // When the script calls a class method, this is called
    5355    virtual int scriptCalling (LuaVirtualMachine& vm, int iFunctionNumber) = 0;
    5456
    55    // When the script function has returns
     57    // When the script function has returns
    5658    virtual void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc) = 0;
    5759
     
    6062    /* ------------------- Handle external Objects ------------------ */
    6163
    62    void removeFromScript(int referenceToScriptable){}
    63    int addScriptableToScript(Scriptable* scriptbl,const std::string& name);  // name= name the scriptable goes by in lua
    64    int addFunctionToScriptable(const std::string& strFuncName, int toScriptable, int lastMethodIndex);
     64    void removeFromScript(int referenceToScriptable){}
     65    int addScriptableToScript(Scriptable* scriptbl,const std::string& name);  // name= name the scriptable goes by in lua
     66    int addFunctionToScriptable(const std::string& strFuncName, int toScriptable, int lastMethodIndex);
    6567
    66    //Handle the Scriptable List
    67    Scriptable* getScriptableByReference(int scrptblRef);
    68    int getReferenceByScriptable(Scriptable* scriptable);
    69    bool addScriptableToList(Scriptable* scriptbl, int scriptableRef);
    70    bool removeScriptableFromList(Scriptable* scriptable);
    71    bool removeScriptableFromList(int scriptable);
     68    //Handle the Scriptable List
     69    Scriptable* getScriptableByReference(int scrptblRef);
     70    int getReferenceByScriptable(Scriptable* scriptable);
     71    bool addScriptableToList(Scriptable* scriptbl, int scriptableRef);
     72    bool removeScriptableFromList(Scriptable* scriptable);
     73    bool removeScriptableFromList(int scriptable);
    7274
    7375
     
    8587    std::string functionName;
    8688    std::list<Scrptbl> scriptableList;
    87 };
     89  };
    8890
     91}
    8992
    9093#endif // __LUA_SCRIPT_BASE_H__
  • branches/script_engine/src/lib/script_engine/This.h

    r7645 r7653  
    66
    77// Sets the "this" global table that scripts use
     8namespace OrxScript
     9{
    810
    9 class LuaThis
    10 {
     11  class LuaThis
     12  {
    1113  public:
    1214    LuaThis (LuaVirtualMachine& vm, int iRef) : oldReference (0), virtualMachine (vm)
     
    1517      if (vm.isOk ())
    1618      {
    17          // Save the old "this" table
     19        // Save the old "this" table
    1820        lua_getglobal (state, "this");
    1921        oldReference = luaL_ref (state, LUA_REGISTRYINDEX);
    2022
    21          // replace it with our new one
     23        // replace it with our new one
    2224        lua_rawgeti(state, LUA_REGISTRYINDEX, iRef);
    2325        lua_setglobal (state, "this");
     
    3032      if (oldReference > 0 && virtualMachine.isOk ())
    3133      {
    32          // Replace the old "this" table
     34        // Replace the old "this" table
    3335        lua_rawgeti(state, LUA_REGISTRYINDEX, oldReference);
    3436        lua_setglobal (state, "this");
     
    4143    int oldReference;
    4244    LuaVirtualMachine& virtualMachine;
    43 };
    44 
     45  };
     46}
    4547#endif // __THIS_H__
  • branches/script_engine/src/lib/script_engine/VirtualMachine.cc

    r7645 r7653  
    55#include "luaincl.h"
    66#include "VirtualMachine.h"
    7 // ---------------------------------------------------------------------------
    8 
    9 
    10 //============================================================================
    11 // int printMessage
    12 //---------------------------------------------------------------------------
    13 // Prints a message to the console
    14 //
    15 // Parameter   Dir      Description
    16 // ---------   ---      -----------
    17 // lua         IN       State variable
    18 //
    19 // Return
    20 // ------
    21 // Number of return varaibles on the stack
    22 //
    23 //============================================================================
    24 static int printMessage (lua_State *lua)
     7namespace OrxScript
    258{
    26   assert (lua_isstring (lua,1));
    27 
    28   const char *msg = lua_tostring (lua, 1);
    29 
    30    // get caller
    31   lua_Debug ar;
    32   memset (&ar, 0, sizeof(ar));
    33   lua_getstack (lua, 1, &ar);
    34   lua_getinfo (lua, "Snl", &ar);
    35 
    36    // debug output
    37   const char *str = ar.source;
    38   printf ("script: %s -- at %s(%d)\n", msg, str, ar.currentline);
    39   return 0;
     9  // ---------------------------------------------------------------------------
     10
     11
     12  //============================================================================
     13  // int printMessage
     14  //---------------------------------------------------------------------------
     15  // Prints a message to the console
     16  //
     17  // Parameter   Dir      Description
     18  // ---------   ---      -----------
     19  // lua         IN       State variable
     20  //
     21  // Return
     22  // ------
     23  // Number of return varaibles on the stack
     24  //
     25  //============================================================================
     26  static int printMessage (lua_State *lua)
     27  {
     28    assert (lua_isstring (lua,1));
     29
     30    const char *msg = lua_tostring (lua, 1);
     31
     32    // get caller
     33    lua_Debug ar;
     34    memset (&ar, 0, sizeof(ar));
     35    lua_getstack (lua, 1, &ar);
     36    lua_getinfo (lua, "Snl", &ar);
     37
     38    // debug output
     39    const char *str = ar.source;
     40    printf ("script: %s -- at %s(%d)\n", msg, str, ar.currentline);
     41    return 0;
     42  }
     43
     44  //============================================================================
     45  // LuaVirtualMachine::LuaVirtualMachine
     46  //---------------------------------------------------------------------------
     47  // Constructor. Setups the default VM state
     48  //
     49  // Parameter   Dir      Description
     50  // ---------   ---      -----------
     51  //
     52  //
     53  // Return
     54  // ------
     55  // None.
     56  //
     57  //============================================================================
     58  LuaVirtualMachine::LuaVirtualMachine (void) : luaState (NULL)
     59  {
     60    machineIsOk = false;
     61  }
     62
     63  //============================================================================
     64  // LuaVirtualMachine::LuaVirtualMachine
     65  //---------------------------------------------------------------------------
     66  // Destructor. Closes the VM
     67  //
     68  // Parameter   Dir      Description
     69  // ---------   ---      -----------
     70  //
     71  //
     72  // Return
     73  // ------
     74  // None.
     75  //
     76  //============================================================================
     77  LuaVirtualMachine::~LuaVirtualMachine (void)
     78  {
     79    if (luaState != NULL)
     80    {
     81      lua_close (luaState);
     82    }
     83  }
     84
     85  //============================================================================
     86  // LuaVirtualMachine::Panic
     87  //---------------------------------------------------------------------------
     88  // When things in Lua go wrong (ever called in protected mode??)
     89  //
     90  // Parameter   Dir      Description
     91  // ---------   ---      -----------
     92  // lua         IN       State variable
     93  //
     94  // Return
     95  // ------
     96  // None.
     97  //
     98  //============================================================================
     99  void LuaVirtualMachine::panic (lua_State *lua)
     100  {}
     101
     102  //============================================================================
     103  // bool LuaVirtualMachine::init
     104  //---------------------------------------------------------------------------
     105  // Initialises the VM, open lua, makes sure things are OK
     106  //
     107  // Parameter   Dir      Description
     108  // ---------   ---      -----------
     109  // None.
     110  //
     111  // Return
     112  // ------
     113  // Success.
     114  //
     115  //============================================================================
     116  bool LuaVirtualMachine::init (void)
     117  {
     118    // Open Lua!
     119    if (isOk ()) destroy ();
     120
     121    luaState = lua_open ();
     122
     123    if (luaState)
     124    {
     125      machineIsOk = true;
     126
     127      // Load util libs into lua
     128      luaopen_base (luaState);
     129      luaopen_table (luaState);
     130      luaopen_string (luaState);
     131      luaopen_math (luaState);
     132      luaopen_debug (luaState);
     133      luaopen_io (luaState);
     134      luaopen_loadlib (luaState);
     135
     136      // setup global printing (trace)
     137      lua_pushcclosure (luaState, printMessage, 0);
     138      lua_setglobal (luaState, "trace");
     139
     140      lua_atpanic (luaState, (lua_CFunction) LuaVirtualMachine::panic);
     141
     142      return true;
     143    }
     144
     145    return false;
     146  }
     147
     148  //============================================================================
     149  // bool LuaVirtualMachine::destroy
     150  //---------------------------------------------------------------------------
     151  // Clears the current Lua state
     152  //
     153  // Parameter   Dir      Description
     154  // ---------   ---      -----------
     155  // None.
     156  //
     157  // Return
     158  // ------
     159  // Success.
     160  //
     161  //============================================================================
     162  bool LuaVirtualMachine::destroy (void)
     163  {
     164    if (luaState)
     165    {
     166      lua_close (luaState);
     167      luaState = NULL;
     168      machineIsOk = false;
     169    }
     170    return true;
     171  }
     172
     173
     174  //============================================================================
     175  // bool LuaVirtualMachine::runFile
     176  //---------------------------------------------------------------------------
     177  // Compiles and runs a lua script file
     178  //
     179  // Parameter   Dir      Description
     180  // ---------   ---      -----------
     181  // strFilename IN       Filename to compile and run
     182  //
     183  // Return
     184  // ------
     185  // Success.
     186  //
     187  //============================================================================
     188  bool LuaVirtualMachine::runFile (const std::string& strFilename)
     189  {
     190    bool fSuccess = false;
     191    int iErr = 0;
     192
     193    if ((iErr = luaL_loadfile (luaState, strFilename.c_str())) == 0)
     194    {
     195      // Call main...
     196      if ((iErr = lua_pcall (luaState, 0, LUA_MULTRET, 0)) == 0)
     197      {
     198        fSuccess = true;
     199      }
     200    }
     201
     202    /* if (fSuccess == false)
     203     {
     204       if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
     205     }
     206    */
     207    return fSuccess;
     208  }
     209
     210  //============================================================================
     211  // bool LuaVirtualMachine::runBuffer
     212  //---------------------------------------------------------------------------
     213  // Compiles and runs a pre-compiled data buffer
     214  //
     215  // Parameter   Dir      Description
     216  // ---------   ---      -----------
     217  // pbBuffer    IN       Buffer to run
     218  // szLen       IN       Length of buffer
     219  // strName     IN       Name of Buffer
     220  //
     221  // Return
     222  // ------
     223  // Success.
     224  //
     225  //============================================================================
     226  bool LuaVirtualMachine::runBuffer (const unsigned char *pbBuffer, size_t szLen, const char *strName /* = NULL */)
     227  {
     228    bool fSuccess = false;
     229    int iErr = 0;
     230
     231    if (strName == NULL)
     232    {
     233      strName = "Temp";
     234    }
     235
     236    if ((iErr = luaL_loadbuffer (luaState, (const char *) pbBuffer, szLen, strName)) == 0)
     237    {
     238      // Call main...
     239      if ((iErr = lua_pcall (luaState, 0, LUA_MULTRET, 0)) == 0)
     240      {
     241        fSuccess = true;
     242      }
     243    }
     244
     245    /* if (fSuccess == false)
     246     {
     247       if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
     248     }
     249    */
     250    return fSuccess;
     251
     252  }
     253
     254  //============================================================================
     255  // LuaVirtualMachine::callFunction
     256  //---------------------------------------------------------------------------
     257  // Calls a function that is already on the stack
     258  //
     259  // Parameter   Dir      Description
     260  // ---------   ---      -----------
     261  // nArgs       IN       Args that are aleady on the stack
     262  // nReturns    IN       Number of expected returns (will be on the stack)
     263  //
     264  // Return
     265  // ------
     266  // Success.
     267  //
     268  //============================================================================
     269  bool LuaVirtualMachine::callFunction (int nArgs, int nReturns /* = 0 */)
     270  {
     271    bool fSuccess = false;
     272
     273    if (lua_isfunction (luaState, -nArgs-1))
     274    {
     275      int iErr = 0;
     276      iErr = lua_pcall (luaState, nArgs, nReturns, 0);
     277
     278      if (iErr == 0)
     279      {
     280        fSuccess = true;
     281      }
     282      /*else
     283      {
     284        if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
     285      }
     286      */
     287    }
     288
     289    return fSuccess;
     290  }
    40291}
    41 
    42 //============================================================================
    43 // LuaVirtualMachine::LuaVirtualMachine
    44 //---------------------------------------------------------------------------
    45 // Constructor. Setups the default VM state
    46 //
    47 // Parameter   Dir      Description
    48 // ---------   ---      -----------
    49 //
    50 //
    51 // Return
    52 // ------
    53 // None.
    54 //
    55 //============================================================================
    56 LuaVirtualMachine::LuaVirtualMachine (void) : luaState (NULL)
    57 {
    58   machineIsOk = false;
    59 }
    60 
    61 //============================================================================
    62 // LuaVirtualMachine::LuaVirtualMachine
    63 //---------------------------------------------------------------------------
    64 // Destructor. Closes the VM
    65 //
    66 // Parameter   Dir      Description
    67 // ---------   ---      -----------
    68 //
    69 //
    70 // Return
    71 // ------
    72 // None.
    73 //
    74 //============================================================================
    75 LuaVirtualMachine::~LuaVirtualMachine (void)
    76 {
    77   if (luaState != NULL)
    78   {
    79     lua_close (luaState);
    80   }
    81 }
    82 
    83 //============================================================================
    84 // LuaVirtualMachine::Panic
    85 //---------------------------------------------------------------------------
    86 // When things in Lua go wrong (ever called in protected mode??)
    87 //
    88 // Parameter   Dir      Description
    89 // ---------   ---      -----------
    90 // lua         IN       State variable
    91 //
    92 // Return
    93 // ------
    94 // None.
    95 //
    96 //============================================================================
    97 void LuaVirtualMachine::panic (lua_State *lua)
    98 {
    99 }
    100 
    101 //============================================================================
    102 // bool LuaVirtualMachine::init
    103 //---------------------------------------------------------------------------
    104 // Initialises the VM, open lua, makes sure things are OK
    105 //
    106 // Parameter   Dir      Description
    107 // ---------   ---      -----------
    108 // None.
    109 //
    110 // Return
    111 // ------
    112 // Success.
    113 //
    114 //============================================================================
    115 bool LuaVirtualMachine::init (void)
    116 {
    117    // Open Lua!
    118   if (isOk ()) destroy ();
    119 
    120   luaState = lua_open ();
    121 
    122   if (luaState)
    123   {
    124     machineIsOk = true;
    125 
    126       // Load util libs into lua
    127     luaopen_base (luaState);
    128     luaopen_table (luaState);
    129     luaopen_string (luaState);
    130     luaopen_math (luaState);
    131     luaopen_debug (luaState);
    132     luaopen_io (luaState);
    133     luaopen_loadlib (luaState);
    134 
    135       // setup global printing (trace)
    136     lua_pushcclosure (luaState, printMessage, 0);
    137     lua_setglobal (luaState, "trace");
    138 
    139     lua_atpanic (luaState, (lua_CFunction) LuaVirtualMachine::panic);
    140 
    141     return true;
    142   }
    143 
    144   return false;
    145 }
    146 
    147 //============================================================================
    148 // bool LuaVirtualMachine::destroy
    149 //---------------------------------------------------------------------------
    150 // Clears the current Lua state
    151 //
    152 // Parameter   Dir      Description
    153 // ---------   ---      -----------
    154 // None.
    155 //
    156 // Return
    157 // ------
    158 // Success.
    159 //
    160 //============================================================================
    161 bool LuaVirtualMachine::destroy (void)
    162 {
    163   if (luaState)
    164   {
    165     lua_close (luaState);
    166     luaState = NULL;
    167     machineIsOk = false;
    168   }
    169   return true;
    170 }
    171 
    172 
    173 //============================================================================
    174 // bool LuaVirtualMachine::runFile
    175 //---------------------------------------------------------------------------
    176 // Compiles and runs a lua script file
    177 //
    178 // Parameter   Dir      Description
    179 // ---------   ---      -----------
    180 // strFilename IN       Filename to compile and run
    181 //
    182 // Return
    183 // ------
    184 // Success.
    185 //
    186 //============================================================================
    187 bool LuaVirtualMachine::runFile (const std::string& strFilename)
    188 {
    189   bool fSuccess = false;
    190   int iErr = 0;
    191 
    192   if ((iErr = luaL_loadfile (luaState, strFilename.c_str())) == 0)
    193   {
    194       // Call main...
    195     if ((iErr = lua_pcall (luaState, 0, LUA_MULTRET, 0)) == 0)
    196     {
    197       fSuccess = true;
    198     }
    199   }
    200 
    201  /* if (fSuccess == false)
    202   {
    203     if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
    204   }
    205  */
    206   return fSuccess;
    207 }
    208 
    209 //============================================================================
    210 // bool LuaVirtualMachine::runBuffer
    211 //---------------------------------------------------------------------------
    212 // Compiles and runs a pre-compiled data buffer
    213 //
    214 // Parameter   Dir      Description
    215 // ---------   ---      -----------
    216 // pbBuffer    IN       Buffer to run
    217 // szLen       IN       Length of buffer
    218 // strName     IN       Name of Buffer
    219 //
    220 // Return
    221 // ------
    222 // Success.
    223 //
    224 //============================================================================
    225 bool LuaVirtualMachine::runBuffer (const unsigned char *pbBuffer, size_t szLen, const char *strName /* = NULL */)
    226 {
    227   bool fSuccess = false;
    228   int iErr = 0;
    229 
    230   if (strName == NULL)
    231   {
    232     strName = "Temp";
    233   }
    234 
    235   if ((iErr = luaL_loadbuffer (luaState, (const char *) pbBuffer, szLen, strName)) == 0)
    236   {
    237       // Call main...
    238     if ((iErr = lua_pcall (luaState, 0, LUA_MULTRET, 0)) == 0)
    239     {
    240       fSuccess = true;
    241     }
    242   }
    243 
    244  /* if (fSuccess == false)
    245   {
    246     if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
    247   }
    248  */
    249   return fSuccess;
    250 
    251 }
    252 
    253 //============================================================================
    254 // LuaVirtualMachine::callFunction
    255 //---------------------------------------------------------------------------
    256 // Calls a function that is already on the stack
    257 //
    258 // Parameter   Dir      Description
    259 // ---------   ---      -----------
    260 // nArgs       IN       Args that are aleady on the stack
    261 // nReturns    IN       Number of expected returns (will be on the stack)
    262 //
    263 // Return
    264 // ------
    265 // Success.
    266 //
    267 //============================================================================
    268 bool LuaVirtualMachine::callFunction (int nArgs, int nReturns /* = 0 */)
    269 {
    270   bool fSuccess = false;
    271 
    272   if (lua_isfunction (luaState, -nArgs-1))
    273   {
    274     int iErr = 0;
    275     iErr = lua_pcall (luaState, nArgs, nReturns, 0);
    276 
    277     if (iErr == 0)
    278     {
    279       fSuccess = true;
    280     }
    281     /*else
    282     {
    283       if (m_pDbg != NULL) m_pDbg->ErrorRun (iErr);
    284     }
    285     */
    286   }
    287 
    288   return fSuccess;
    289 }
  • branches/script_engine/src/lib/script_engine/VirtualMachine.h

    r7645 r7653  
    55
    66#include "luaincl.h"
    7 
    8 class LuaVirtualMachine
     7namespace OrxScript
    98{
     9  class LuaVirtualMachine
     10  {
    1011  public:
    1112    LuaVirtualMachine (void);
     
    1516    bool destroy (void);
    1617
    17    // Load and run script elements
     18    // Load and run script elements
    1819    bool runFile (const std::string& strFilename);
    1920    bool runBuffer (const unsigned char *pbBuffer, size_t szLen, const char *strName = NULL);
    2021
    21    // C-Api into script
     22    // C-Api into script
    2223    bool callFunction (int nArgs, int nReturns = 0);
    2324
    24    // Get the state of the lua stack (use the cast operator)
    25    //lua_State *GetState (void) { return luaState; }
     25    // Get the state of the lua stack (use the cast operator)
     26    //lua_State *GetState (void) { return luaState; }
    2627    operator lua_State *(void) { return luaState; }
    2728
    2829    static void panic (lua_State *lua);
    2930
    30    // Check if the VM is OK and can be used still
     31    // Check if the VM is OK and can be used still
    3132    virtual bool isOk (void) { return machineIsOk; }
    3233
    33    // For debugging
     34    // For debugging
    3435    //void AttachDebugger (CLuaDebugger *dbg) { m_pDbg = dbg; }
    3536
     
    3738    lua_State* luaState;
    3839    bool machineIsOk;
    39    // CLuaDebugger *m_pDbg;
    40 };
     40    // CLuaDebugger *m_pDbg;
     41  };
     42}
    4143#endif
  • branches/script_engine/src/lib/script_engine/main.cc

    r7645 r7653  
    1313
    1414
    15 
     15using namespace OrxScript;
    1616
    1717//HACK !!!
  • branches/script_engine/src/lib/script_engine/scriptable.cc

    r7645 r7653  
    99
    1010// ---------------------------------------------------------------------------
    11 
    12 /**
    13  * @brief Constructor
    14  *
    15  */
    16 Scriptable::Scriptable ()
     11namespace OrxScript
    1712{
    18 
    19 }
    20 
    21 /**
    22  * @brief Deconstructor
    23  *
    24  * The Deconstructor tells all the scripts, that it is part of, that it is deleted.
    25  *
    26  */
    27 Scriptable::~Scriptable (void)
    28 {
    29   std::list<Script>::iterator it;
    30   for(it = scriptList.begin();it != scriptList.end(); it++)
    31    {
    32      (*it).script->removeFromScript((*it).thisReference);
    33    }
    34 
    35 }
    36 
    37 
    38 //Method indexing check
    39     int Scriptable::methods (LuaVirtualMachine& virtualMachine)
    40     {
    41       LuaScript* script =(getScriptByVirtualMachine(virtualMachine))->script;
     13  /**
     14   * @brief Constructor
     15   *
     16   */
     17  Scriptable::Scriptable ()
     18  {
     19  }
     20
     21  /**
     22   * @brief Deconstructor
     23   *
     24   * The Deconstructor tells all the scripts, that it is part of, that it is deleted.
     25   *
     26   */
     27  Scriptable::~Scriptable (void)
     28  {
     29    std::list<Script>::iterator it;
     30    for(it = scriptList.begin();it != scriptList.end(); it++)
     31    {
     32      (*it).script->removeFromScript((*it).thisReference);
     33    }
     34
     35  }
     36
     37
     38  //Method indexing check
     39  int Scriptable::methods (LuaVirtualMachine& virtualMachine)
     40  {
     41    LuaScript* script =(getScriptByVirtualMachine(virtualMachine))->script;
     42    if(script)
     43    {
     44      int lastMethod = getLastMethodIndexByPointer(script);
     45      if(lastMethod != -1)
     46        return lastMethod;
     47    }
     48
     49    return -1;
     50  }
     51
     52
     53  /**
     54   * @brief  Tells the scriptable that it got added to a script
     55   * @param  toScript a pointer to the script the object got added
     56   * @param
     57   * @param  reference a reference to the scriptable in that partilular script
     58   *
     59   *  The scriptable will register all its functions to the table at "reference"
     60   *  with the script.
     61   *
     62   */
     63
     64  bool Scriptable::scriptableAdded(LuaScript* toScript, int toScriptRef, int reference)
     65  {
     66
     67    bool success = true ;
     68    if(!scriptIsInScriptList(toScript))// look if the scriptable isn't already added.
     69      if(toScript)
     70      {
     71        Script newScript;
     72        newScript.script = toScript;
     73        newScript.scriptReference = toScriptRef;
     74        newScript.thisReference = reference;
     75        newScript.lastMethodIndex = -1;
     76        newScript.methodBase = -1;
     77
     78        scriptList.push_back(newScript);
     79
     80        int methodIndex;
     81        Script* tmpScript = getScriptByPointer(toScript);
     82
     83        //add all the functions to the script
     84        std::list<std::string>::const_iterator it;
     85
     86        for(it = functionList.begin();it != functionList.end(); it++)
     87        {
     88
     89          if(tmpScript)
     90          {
     91            methodIndex = toScript->addFunctionToScriptable(*it, tmpScript->thisReference, tmpScript->lastMethodIndex);
     92
     93
     94            if(newScript.methodBase = -1)
     95            {
     96              if(methodIndex != -1)
     97              {
     98                std::cout<<"methodIndex is "<<methodIndex<<std::endl;
     99                tmpScript->methodBase= methodIndex;
     100                tmpScript->lastMethodIndex= methodIndex;
     101                tmpScript->functionMap[newScript.methodBase] = *it;
     102              }
     103              else{success = false; break;}
     104            }
     105
     106            else if(methodIndex != -1)
     107            {
     108
     109              tmpScript->lastMethodIndex = methodIndex;
     110              tmpScript->functionMap[newScript.lastMethodIndex] = *it;
     111            }
     112            else{success= false;break;}
     113
     114          }
     115        }
     116
     117
     118
     119      }
     120      else
     121      {
     122        success = false;
     123      }
     124
     125    return success;
     126
     127  }
     128
     129
     130
     131  /**
     132    * @brief  Register a function with the scriptable
     133    * @param  functionName function name
     134    *
     135    *
     136   */
     137
     138  void Scriptable::registerFunction(std::string functionName)
     139  {
     140    //check whether the function is already registered
     141    std::list<std::string>::iterator it;
     142    for(it = functionList.begin();it != functionList.end(); it++)
     143    {
     144      if((*it).compare(functionName) == 0)
     145      {
     146        break;
     147      }
     148
     149    }
     150
     151    if(it == functionList.end()) // if the functoin wasn't found
     152      functionList.push_back(functionName);
     153  }
     154
     155
     156  /**
     157   * @brief  Get the function name of the function at index
     158   * @param  index
     159   *
     160   * @return the function name on success.
     161   *
     162   * This function is used in the ScriptCalling function
     163   */
     164  std::string Scriptable::getFunctionAtIndex(int index, LuaVirtualMachine& virtualMachine)
     165  {
     166    lua_State * luaState = (lua_State* ) virtualMachine;
     167
     168    if(virtualMachine.isOk())
     169    {
     170      lua_getglobal (luaState, "this");
     171
     172      if (lua_istable (luaState, 1))
     173      {
     174        // Found the "this" table. The object pointer is at the index 0
     175        lua_rawgeti (luaState, 1, 0);
     176
     177        if (lua_islightuserdata (luaState, -1))
     178        {
     179          // Found the pointer, need to cast it
     180          LuaScript* thisPointer = (LuaScript *) lua_touserdata (luaState, -1);
     181
     182          if(thisPointer != NULL)
     183          {
     184            Script* script = getScriptByPointer(thisPointer);
     185            if( script != NULL)
     186            {
     187              std::map<int, std::string>::const_iterator it = script->functionMap.find(index);
     188              if(it != script->functionMap.end())//if found
     189                return script->functionMap[index];
     190            }
     191
     192          }
     193        }
     194      }
     195    }
     196
     197  }
     198
     199
     200  /**
     201   * @brief Gets the lastMethod index associated with the LuaScript
     202   * @param the luaScript
     203   *
     204   * @return  A lua reference to the last function of the Scriptable
     205   *
     206   *
     207   */
     208
     209  int Scriptable::getLastMethodIndexByPointer(LuaScript* luaScript)
     210  {
     211    if( luaScript )
     212    {
     213      Script* script = (getScriptByPointer(luaScript));
    42214      if(script)
    43215      {
    44         int lastMethod = getLastMethodIndexByPointer(script);
    45         if(lastMethod != -1)
    46           return lastMethod;
    47       }
    48 
    49       return -1;
    50     }
    51 
    52 
    53 /**
    54  * @brief  Tells the scriptable that it got added to a script
    55  * @param  toScript a pointer to the script the object got added
    56  * @param
    57  * @param  reference a reference to the scriptable in that partilular script
    58  *
    59  *  The scriptable will register all its functions to the table at "reference"
    60  *  with the script.
    61  *
    62  */
    63 
    64 bool Scriptable::scriptableAdded(LuaScript* toScript, int toScriptRef, int reference)
    65  {
    66 
    67    bool success = true ;
    68    if(!scriptIsInScriptList(toScript))// look if the scriptable isn't already added.
    69    if(toScript)
    70    {
    71      Script newScript;
    72      newScript.script = toScript;
    73      newScript.scriptReference = toScriptRef;
    74      newScript.thisReference = reference;
    75      newScript.lastMethodIndex = -1;
    76      newScript.methodBase = -1;
    77 
    78      scriptList.push_back(newScript);
    79 
    80      int methodIndex;
    81      Script* tmpScript = getScriptByPointer(toScript);
    82 
    83     //add all the functions to the script
    84      std::list<std::string>::const_iterator it;
    85 
    86      for(it = functionList.begin();it != functionList.end(); it++)
    87       {
    88 
    89         if(tmpScript)
    90          {
    91         methodIndex = toScript->addFunctionToScriptable(*it, tmpScript->thisReference, tmpScript->lastMethodIndex);
    92 
    93 
    94         if(newScript.methodBase = -1)
    95         {
    96           if(methodIndex != -1)
    97           {
    98             std::cout<<"methodIndex is "<<methodIndex<<std::endl;
    99             tmpScript->methodBase= methodIndex;
    100             tmpScript->lastMethodIndex= methodIndex;
    101             tmpScript->functionMap[newScript.methodBase] = *it;
    102            }
    103            else{success = false; break;}
    104         }
    105 
    106         else if(methodIndex != -1)
    107           {
    108 
    109             tmpScript->lastMethodIndex = methodIndex;
    110             tmpScript->functionMap[newScript.lastMethodIndex] = *it;
    111           }
    112         else{success= false;break;}
    113 
    114          }
    115       }
    116 
    117 
    118 
    119    }
    120    else
    121    {
    122      success = false;
    123    }
    124 
    125    return success;
    126 
    127  }
    128 
    129 
    130 
    131 /**
    132   * @brief  Register a function with the scriptable
    133   * @param  functionName function name
    134   *
    135   *
    136  */
    137 
    138  void Scriptable::registerFunction(std::string functionName)
    139  {
    140    //check whether the function is already registered
    141    std::list<std::string>::iterator it;
    142    for(it = functionList.begin();it != functionList.end(); it++)
    143    {
    144      if((*it).compare(functionName) == 0)
    145      {
    146        break;
    147      }
    148 
    149    }
    150 
    151    if(it == functionList.end()) // if the functoin wasn't found
    152    functionList.push_back(functionName);
    153  }
    154 
    155 
    156  /**
    157   * @brief  Get the function name of the function at index
    158   * @param  index
    159   *
    160   * @return the function name on success.
    161   *
    162   * This function is used in the ScriptCalling function
    163   */
    164 std::string Scriptable::getFunctionAtIndex(int index, LuaVirtualMachine& virtualMachine)
    165 {
    166   lua_State * luaState = (lua_State* ) virtualMachine;
    167 
    168   if(virtualMachine.isOk())
    169   {
    170     lua_getglobal (luaState, "this");
    171 
    172     if (lua_istable (luaState, 1))
    173     {
    174    // Found the "this" table. The object pointer is at the index 0
    175       lua_rawgeti (luaState, 1, 0);
    176 
    177       if (lua_islightuserdata (luaState, -1))
    178       {
    179      // Found the pointer, need to cast it
    180         LuaScript* thisPointer = (LuaScript *) lua_touserdata (luaState, -1);
    181 
    182         if(thisPointer != NULL)
    183         {
    184           Script* script = getScriptByPointer(thisPointer);
    185           if( script != NULL)
    186           {
    187            std::map<int, std::string>::const_iterator it = script->functionMap.find(index);
    188            if(it != script->functionMap.end())//if found
    189             return script->functionMap[index];
    190           }
    191 
    192         }
    193       }
    194     }
    195   }
    196 
    197 }
    198 
    199 
    200 /**
    201  * @brief Gets the lastMethod index associated with the LuaScript
    202  * @param the luaScript
    203  *
    204  * @return  A lua reference to the last function of the Scriptable
    205  *
    206  *
    207  */
    208 
    209  int Scriptable::getLastMethodIndexByPointer(LuaScript* luaScript)
    210   {
    211     if( luaScript )
    212     {
    213       Script* script = (getScriptByPointer(luaScript));
    214      if(script)
    215      {
    216        return (script->lastMethodIndex);
    217      }
    218    }
    219 
    220    return -1;
     216        return (script->lastMethodIndex);
     217      }
     218    }
     219
     220    return -1;
    221221  }
    222222
     
    231231   */
    232232
    233  std::map<int, std::string>* Scriptable::getFunctionMapByPointer(LuaScript* scriptPointer)
    234  {
    235    bool notFound = true;
    236    if(scriptPointer)
    237    {
    238     std::list<Script>::iterator it = scriptList.begin();
    239 
    240 
    241     while(notFound && it !=scriptList.end() )
    242     {
    243      if((*it).script == scriptPointer)
    244      {
    245        notFound = false;
    246        return &(it->functionMap);
    247      }
    248      it++;
    249     }
    250    }
    251 
    252    if(notFound)
    253     return NULL;
    254 
    255  }
    256 
    257 
    258  /**
    259   * @brief Gets the internal representation of a LuaScript by its pointer.
    260   * @param script the LuaScript
    261   *
    262   * @return returns the script if it was found, NULL else.
    263   *
    264   *
    265   */
    266 
    267  Script* Scriptable::getScriptByPointer(LuaScript* script)
    268  {
    269    bool notFound = true;
    270 
    271    if(script)
    272    {
    273     std::list<Script>::iterator it = scriptList.begin();
    274 
    275     while(notFound && it != scriptList.end() )
    276     {
    277      if((*it).script == script)
    278      {
    279        notFound = false;
    280        return &(*it);
    281      }
    282      it++;
    283     }
    284 
    285    }
    286    if(notFound)
    287      return NULL;
    288 
    289  }
    290 
    291 
    292  /**
    293   * @brief Extracts the Script out of the virtual machine
    294   * @param virtualMachine the virtualMachine to search for the script
    295   *
    296   * @return The Script. If there was an error it returns NULL
    297   *
    298   *
    299   */
    300  Script* Scriptable::getScriptByVirtualMachine(LuaVirtualMachine& virtualMachine)
    301  {
    302 
    303    if(virtualMachine.isOk())
    304    {
    305      lua_State * luaState = (lua_State* ) virtualMachine;
    306      lua_getglobal (luaState, "this");
    307 
    308      if (lua_istable (luaState, 1))
    309      {
    310    // Found the "this" table. The object pointer is at the index 0
    311        lua_rawgeti (luaState, 1, 0);
    312 
    313        if (lua_islightuserdata (luaState, -1))
    314        {
    315      // Found the pointer, need to cast it
    316          LuaScript* thisPointer = (LuaScript *) lua_touserdata (luaState, -1);
    317          Script* script = getScriptByPointer(thisPointer);
    318 
    319          if(script)
    320           return script;
    321          else
    322           return NULL;
    323        }
    324      }
    325    }
    326 
    327 
    328  }
    329 
    330 
    331  /**
    332   * @brief Checks if "this" Scriptable is already registred with a LuaScript
    333   * @param script The LuaScript
    334   *
    335   * @return true when the Scriptable is alreads registered with that script, flase else.
    336   *
    337   *
    338   */
    339  bool Scriptable::scriptIsInScriptList(LuaScript* script)
    340  {
    341    bool notFound = true;
    342 
    343    if(script)
    344    {
    345    std::list<Script>::iterator it = scriptList.begin();
    346 
    347 
    348    while( notFound && it !=scriptList.end() )
    349      {
    350        if((*it).script == script)
    351         {
    352        notFound = false;
    353        break;
    354         }
    355      it++;
    356     }
    357 
    358    }
    359    return !notFound;
    360 
    361  }
    362 
    363 
    364  /**
    365   * @brief Removes a LuaScript from the scriptList
    366   * @param deleted LuaScript that is about to be deleted
    367   *
    368   * This function has to be called int the destructor of the LuaScript.
    369   *
    370   *
    371   */
    372 
    373 void Scriptable::scriptDeleted(LuaScript* deleted)
    374 {
    375   if(deleted)
    376   {
    377     Script* script = getScriptByPointer(deleted);
     233  std::map<int, std::string>* Scriptable::getFunctionMapByPointer(LuaScript* scriptPointer)
     234  {
     235    bool notFound = true;
     236    if(scriptPointer)
     237    {
     238      std::list<Script>::iterator it = scriptList.begin();
     239
     240
     241      while(notFound && it !=scriptList.end() )
     242      {
     243        if((*it).script == scriptPointer)
     244        {
     245          notFound = false;
     246          return &(it->functionMap);
     247        }
     248        it++;
     249      }
     250    }
     251
     252    if(notFound)
     253      return NULL;
     254
     255  }
     256
     257
     258  /**
     259   * @brief Gets the internal representation of a LuaScript by its pointer.
     260   * @param script the LuaScript
     261   *
     262   * @return returns the script if it was found, NULL else.
     263   *
     264   *
     265   */
     266
     267  Script* Scriptable::getScriptByPointer(LuaScript* script)
     268  {
     269    bool notFound = true;
     270
    378271    if(script)
    379      {
    380        std::list<Script>::iterator it = scriptList.begin();
    381 
    382 
    383        while((*it).script != deleted && it != scriptList.end() )
    384        {
    385          it++;
    386        }
    387 
    388        if(it != scriptList.end())
     272    {
     273      std::list<Script>::iterator it = scriptList.begin();
     274
     275      while(notFound && it != scriptList.end() )
     276      {
     277        if((*it).script == script)
     278        {
     279          notFound = false;
     280          return &(*it);
     281        }
     282        it++;
     283      }
     284
     285    }
     286    if(notFound)
     287      return NULL;
     288
     289  }
     290
     291
     292  /**
     293   * @brief Extracts the Script out of the virtual machine
     294   * @param virtualMachine the virtualMachine to search for the script
     295   *
     296   * @return The Script. If there was an error it returns NULL
     297   *
     298   *
     299   */
     300  Script* Scriptable::getScriptByVirtualMachine(LuaVirtualMachine& virtualMachine)
     301  {
     302
     303    if(virtualMachine.isOk())
     304    {
     305      lua_State * luaState = (lua_State* ) virtualMachine;
     306      lua_getglobal (luaState, "this");
     307
     308      if (lua_istable (luaState, 1))
     309      {
     310        // Found the "this" table. The object pointer is at the index 0
     311        lua_rawgeti (luaState, 1, 0);
     312
     313        if (lua_islightuserdata (luaState, -1))
     314        {
     315          // Found the pointer, need to cast it
     316          LuaScript* thisPointer = (LuaScript *) lua_touserdata (luaState, -1);
     317          Script* script = getScriptByPointer(thisPointer);
     318
     319          if(script)
     320            return script;
     321          else
     322            return NULL;
     323        }
     324      }
     325    }
     326
     327
     328  }
     329
     330
     331  /**
     332   * @brief Checks if "this" Scriptable is already registred with a LuaScript
     333   * @param script The LuaScript
     334   *
     335   * @return true when the Scriptable is alreads registered with that script, flase else.
     336   *
     337   *
     338   */
     339  bool Scriptable::scriptIsInScriptList(LuaScript* script)
     340  {
     341    bool notFound = true;
     342
     343    if(script)
     344    {
     345      std::list<Script>::iterator it = scriptList.begin();
     346
     347
     348      while( notFound && it !=scriptList.end() )
     349      {
     350        if((*it).script == script)
     351        {
     352          notFound = false;
     353          break;
     354        }
     355        it++;
     356      }
     357
     358    }
     359    return !notFound;
     360
     361  }
     362
     363
     364  /**
     365   * @brief Removes a LuaScript from the scriptList
     366   * @param deleted LuaScript that is about to be deleted
     367   *
     368   * This function has to be called int the destructor of the LuaScript.
     369   *
     370   *
     371   */
     372
     373  void Scriptable::scriptDeleted(LuaScript* deleted)
     374  {
     375    if(deleted)
     376    {
     377      Script* script = getScriptByPointer(deleted);
     378      if(script)
     379      {
     380        std::list<Script>::iterator it = scriptList.begin();
     381
     382
     383        while((*it).script != deleted && it != scriptList.end() )
     384        {
     385          it++;
     386        }
     387
     388        if(it != scriptList.end())
    389389        {
    390390          scriptList.erase(it);
     
    392392
    393393
    394      }
    395   }
    396 
     394      }
     395    }
     396
     397  }
     398
     399
     400
     401  char Scriptable::whatIsThis()
     402  {
     403    char result = 's';
     404    return result;
     405  }
    397406}
    398 
    399 
    400 
    401 char Scriptable::whatIsThis()
    402  {
    403    char result = 's';
    404    return result;
    405  }
  • branches/script_engine/src/lib/script_engine/scriptable.h

    r7645 r7653  
    99#include "luaincl.h"
    1010
    11 class LuaScript;
     11namespace OrxScript
     12{
     13  class LuaScript;
    1214
    13 //internal representation of a LuaScript
    14 struct Script
     15  //internal representation of a LuaScript
     16  struct Script
    1517  {
    1618    int lastMethodIndex;
     
    2224  };
    2325
    24 class Scriptable
    25 {
     26  class Scriptable
     27  {
    2628  public:
    2729    Scriptable (void);
    2830    virtual ~Scriptable (void);
    2931
    30    // Method indexing check
    31    int methods (LuaVirtualMachine& virtualMachine);
     32    // Method indexing check
     33    int methods (LuaVirtualMachine& virtualMachine);
    3234    //int methods(){;return 1;} //BAD BAD HACK HACK HACK !!!!!!!!!!!!!!
    3335
    3436    char whatIsThis();
    3537
    36    // When the script calls a class method, this is called
     38    // When the script calls a class method, this is called
    3739    virtual int scriptCalling (LuaVirtualMachine& vm, std::string functionName) = 0;
    3840
    39    // When the script function has returns
     41    // When the script function has returns
    4042    virtual void handleReturns (LuaVirtualMachine& vm, const std::string& strFunc) = 0;
    4143
     
    4547    void registerFunction(std::string functionName);//Adds a function to the internal function list
    4648  private:
    47    bool scriptableAdded(LuaScript* script, int scriptRef, int reference);
    48    //void scriptableFunctionAdded(LuaScript* script, int reference);
     49    bool scriptableAdded(LuaScript* script, int scriptRef, int reference);
     50    //void scriptableFunctionAdded(LuaScript* script, int reference);
    4951
    5052
    51    Script* getScriptByPointer(LuaScript* script);
    52    Script* getScriptByVirtualMachine(LuaVirtualMachine& virtualMachine);
    53    std::map<int, std::string>* getFunctionMapByPointer(LuaScript* scriptPointer);
    54    int getLastMethodIndexByPointer(LuaScript* script);
     53    Script* getScriptByPointer(LuaScript* script);
     54    Script* getScriptByVirtualMachine(LuaVirtualMachine& virtualMachine);
     55    std::map<int, std::string>* getFunctionMapByPointer(LuaScript* scriptPointer);
     56    int getLastMethodIndexByPointer(LuaScript* script);
    5557
    5658
    57    bool scriptIsInScriptList(LuaScript* script);
     59    bool scriptIsInScriptList(LuaScript* script);
    5860
    59    void scriptDeleted(LuaScript* deleted);
     61    void scriptDeleted(LuaScript* deleted);
    6062
    6163
    62   friend class LuaScript;
     64    friend class LuaScript;
    6365
    6466    std::list<std::string> functionList;
    6567    std::list<Script> scriptList;
    66 };
     68  };
    6769
     70}
    6871
    6972#endif // __SCRIPTABLE_H__
Note: See TracChangeset for help on using the changeset viewer.