Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/script_trigger/src/core/LuaBind.cc @ 1904

Last change on this file since 1904 was 1904, checked in by rgrieder, 16 years ago

Tiny correction. The branch now compiles runs on my box.

File size: 8.6 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Benjamin Knecht
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "LuaBind.h"
30
31#include <fstream>
32#include <map>
33
34#include "CoreIncludes.h"
35
36extern "C" {
37#include <lualib.h>
38#include <lauxlib.h>
39}
40
41#include "tolua/tolua++.h"
42#include "tolua/tolua_bind.h"
43
44namespace orxonox
45{
46  LuaBind* LuaBind::singletonRef = NULL;
47
48  LuaBind::LuaBind()
49  {
50    luaState_ = lua_open();
51    luaSource_ = "";
52#if LUA_VERSION_NUM == 501
53    luaL_openlibs(luaState_);
54#else
55    luaopen_base(luaState_);
56    luaopen_string(luaState_);
57    luaopen_table(luaState_);
58    luaopen_math(luaState_);
59    luaopen_io(luaState_);
60    luaopen_debug(luaState_);
61#endif
62    tolua_core_open(luaState_);
63    output_ = "";
64    isRunning_ = false;
65  }
66
67  void LuaBind::luaPrint(std::string str)
68  {
69    output_ += str;
70    COUT(4) << "Lua_output!:" << std::endl << str << std::endl << "***" << std::endl;
71  }
72
73  /**
74      @brief Loads the specified file line by line
75      @param filename The filename of the file
76      @param luaTags if true, the loaded file gets stripped off luaTags
77  */
78  void LuaBind::loadFile(std::string filename, bool luaTags)
79  {
80    output_ = "";
81    std::ifstream file;
82    file.open(filename.c_str(), std::fstream::in);
83
84    if (!file.is_open())
85    {
86      // some error msg
87    }
88
89    char line[1024];
90    std::string levelString = "";
91
92    while (file.good() && !file.eof())
93    {
94      file.getline(line, 1024);
95      levelString += line;
96      levelString += "\n";
97    }
98
99    file.close();
100    //std::string output;
101
102    if (luaTags) luaSource_ = replaceLuaTags(levelString);
103    COUT(4) << "ParsedSourceCode: " << luaSource_ << std::endl;
104  }
105
106  void LuaBind::loadString(std::string code)
107  {
108    luaSource_ = code;
109    output_ = "";
110  }
111
112#if LUA_VERSION_NUM != 501
113  const char * LuaBind::lua_Chunkreader(lua_State *L, void *data, size_t *size)
114  {
115    LoadS* ls = ((LoadS*)data);
116    if (ls->size == 0) return NULL;
117    *size = ls->size;
118    ls->size = 0;
119    return ls->s;
120  }
121#endif
122  void LuaBind::run()
123  {
124    if (!isRunning_)
125    {
126      isRunning_ = true;
127      int error = 0;
128      std::string init = "local scr = orxonox.LuaBind:getInstance()\nlocal debug = print\nprint = function(s)\nscr:luaPrint(s)\nend\ninclude = function(f)\nfile = io.open(f)\ncontent = file:read(\"*a\")\nfile:close()\nsource = scr:replaceLuaTags(content)\ndebug(source)\nassert(loadstring(source))()\nend\n";
129      init += luaSource_;
130  #if LUA_VERSION_NUM == 501
131      error = luaL_loadstring(luaState_, init.c_str());
132  #else
133      LoadS ls;
134      ls.s = init.c_str();
135      ls.size = init.size();
136      error = lua_load(luaState_, &orxonox::LuaBind::lua_Chunkreader, &ls, init.c_str());
137  #endif
138      if (error == 0)
139      {
140        error = lua_pcall(luaState_, 0, 0, 0);
141      }
142      if (error != 0)
143      {
144        COUT(2) << "Error in Lua-script: " << lua_tostring(luaState_, -1) << std::endl;
145      }
146      isRunning_ = false;
147    }
148    else
149    {
150      COUT(2) << "Warning: Lua's run is called while running!" << std::endl;
151    }
152  }
153
154  unsigned int LuaBind::getNextQuote(const std::string& text, unsigned int start)
155  {
156    unsigned int quote = start - 1;
157
158    while ((quote = text.find('\"', quote + 1)) != std::string::npos)
159    {
160      unsigned int backslash = quote;
161      unsigned int numbackslashes = 0;
162      for (; backslash > 0; backslash--, numbackslashes++)
163        if (text[backslash - 1] != '\\')
164          break;
165
166      if (numbackslashes % 2 == 0)
167        break;
168    }
169
170    return quote;
171  }
172
173  std::string LuaBind::replaceLuaTags(const std::string& text)
174  {
175    // chreate map with all Lua tags
176    std::map<unsigned int, bool> luaTags;
177    {
178      unsigned int pos = 0;
179      while ((pos = text.find("<?lua", pos)) != std::string::npos)
180        luaTags[pos++] = true;
181    }
182    {
183      unsigned int pos = 0;
184      while ((pos = text.find("?>", pos)) != std::string::npos)
185        luaTags[pos++] = false;
186    }
187
188    // erase all tags from the map that are between two quotes
189    {
190      std::map<unsigned int, bool>::iterator it = luaTags.begin();
191      std::map<unsigned int, bool>::iterator it2 = it;
192      bool bBetweenQuotes = false;
193      unsigned int pos = 0;
194      while ((pos = getNextQuote(text, pos)) != std::string::npos)
195      {
196        while ((it != luaTags.end()) && (it->first < pos))
197        {
198          if (bBetweenQuotes) {
199            it2++;
200            if(it->second && !(it2->second) && it2->first < pos)
201              it = ++it2;
202            else
203              luaTags.erase(it++);
204          }
205          else
206            ++it;
207        }
208        bBetweenQuotes = !bBetweenQuotes;
209        pos++;
210      }
211    }
212
213    // check whether on every opening <?lua tag a closing ?> tag follows
214    {
215      bool expectedValue = true;
216      for (std::map<unsigned int, bool>::iterator it = luaTags.begin(); it != luaTags.end(); ++it)
217      {
218        if ((*it).second == expectedValue)
219          expectedValue = !expectedValue;
220        else
221        {
222          expectedValue = false;
223          break;
224        }
225      }
226      if (!expectedValue) {
227        COUT(2) << "Warning: Error in level file" << std::endl;
228        // todo: errorhandling
229        return "";
230      }
231    }
232
233    // cut the original string into pieces and put them together with print() instead of lua tags
234    std::string output;
235    {
236      std::map<unsigned int, bool>::iterator it = luaTags.begin();
237      bool bInPrintFunction = true;
238      unsigned int start = 0;
239      unsigned int end = 0;
240
241      do
242      {
243        if (it != luaTags.end())
244          end = (*(it++)).first;
245        else
246          end = std::string::npos;
247
248        unsigned int equalSignCounter = 0;
249
250        if (bInPrintFunction)
251        {
252          // count ['='[ and ]'='] and replace tags with print([[ and ]])
253          std::string temp = text.substr(start, end - start);
254          {
255            unsigned int pos = 0;
256            while ((pos = temp.find('[', pos)) != std::string::npos)
257            {
258              unsigned int tempCounter = 1;
259              unsigned int tempPos = pos++;
260              while(temp[++tempPos] == '=') {
261                tempCounter++;
262              }
263              if(temp[tempPos] != '[') {
264                tempCounter = 0;
265              }
266              else if(tempCounter == 0) {
267                tempCounter = 1;
268              }
269              if (tempCounter > equalSignCounter)
270                equalSignCounter = tempCounter;
271            }
272          }
273          {
274            unsigned int pos = 0;
275            while ((pos = temp.find(']', pos)) != std::string::npos)
276            {
277              unsigned int tempCounter = 1;
278              unsigned int tempPos = pos++;
279              while(temp[++tempPos] == '=') {
280                tempCounter++;
281              }
282              if(temp[tempPos] != ']') {
283                tempCounter = 0;
284              }
285              else if(tempCounter == 0) {
286                tempCounter = 1;
287              }
288              if (tempCounter > equalSignCounter)
289                equalSignCounter = tempCounter;
290            }
291          }
292          std::string equalSigns = "";
293          for(unsigned int i = 0; i < equalSignCounter; i++) {
294            equalSigns += "=";
295          }
296          output += "print([" + equalSigns + "[" + temp + "]" + equalSigns +"])";
297          start = end + 5;
298        }
299        else
300        {
301          output += text.substr(start, end - start);
302          start = end + 2;
303        }
304
305        bInPrintFunction = !bInPrintFunction;
306      }
307      while (end != std::string::npos);
308    }
309
310    return output;
311  }
312
313}
Note: See TracBrowser for help on using the repository browser.