Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib/src/libraries/core/LuaState.cc @ 8324

Last change on this file since 8324 was 7945, checked in by rgrieder, 14 years ago

Removed workarounds for Lua 5.0 in LuaState class.

  • Property svn:eol-style set to native
File size: 11.5 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 *      Reto Grieder
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30#include "LuaState.h"
31
32#include <tolua++.h>
33extern "C" {
34#include <lua.h>
35#include <lualib.h>
36}
37#include <loki/ScopeGuard.h>
38
39#include "util/Debug.h"
40#include "util/Exception.h"
41#include "Resource.h"
42#include "ToluaBindCore.h"
43#include "command/IOConsole.h"
44
45namespace orxonox
46{
47    LuaState::ToluaInterfaceMap LuaState::toluaInterfaces_s;
48    std::vector<LuaState*> LuaState::instances_s;
49
50    const std::string LuaState::ERROR_HANDLER_NAME = "errorHandler";
51
52    // Do this after declaring toluaInterfaces_s and instances_s to avoid larger problems
53    DeclareToluaInterface(Core);
54
55    LuaState::LuaState()
56        : bIsRunning_(false)
57        , includeParseFunction_(NULL)
58    {
59        // Create new lua state and configure it
60        luaState_ = lua_open();
61        Loki::ScopeGuard luaStateGuard = Loki::MakeGuard(&lua_close, luaState_);
62        luaL_openlibs(luaState_);
63
64        // Open all available tolua interfaces
65        this->openToluaInterfaces(luaState_);
66
67        // Create dummy file info
68        sourceFileInfo_.reset(new ResourceInfo());
69        sourceFileInfo_->group = "General";
70        sourceFileInfo_->size = 0;
71
72        // Push 'this' pointer
73        tolua_pushusertype(luaState_, static_cast<void*>(this), "orxonox::LuaState");
74        lua_setglobal(luaState_, "luaState");
75
76        // Parse init script
77        if (!this->doFile("LuaStateInit.lua"))
78            ThrowException(InitialisationFailed, "Running LuaStateInit.lua failed");
79
80        luaStateGuard.Dismiss();
81    }
82
83    LuaState::~LuaState()
84    {
85        lua_close(luaState_);
86    }
87
88    shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename)
89    {
90        // Look in the current directory first
91        shared_ptr<ResourceInfo> sourceInfo = Resource::getInfo(sourceFileInfo_->path + filename);
92        // Continue search in root directories
93        if (sourceInfo == NULL && !sourceFileInfo_->path.empty())
94            sourceInfo = Resource::getInfo(filename);
95        return sourceInfo;
96    }
97
98    bool LuaState::includeFile(const std::string& filename)
99    {
100        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename);
101        if (sourceInfo != NULL)
102            return this->includeString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
103        else
104        {
105            COUT(2) << "LuaState: Cannot include file '" << filename << "' (not found)." << std::endl;
106            return false;
107        }
108    }
109
110    bool LuaState::includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
111    {
112        // Parse string with provided include parser (otherwise don't preparse at all)
113        std::string luaInput;
114        if (includeParseFunction_ != NULL)
115            luaInput = (*includeParseFunction_)(code);
116        else
117            luaInput = code;
118
119        if (sourceFileInfo != NULL)
120        {
121            // Also fill a map with the actual source code. This is just for the include* commands
122            // where the content of sourceFileInfo->filename doesn't match 'code'
123            this->sourceCodeMap_[sourceFileInfo->filename] = code;
124        }
125
126        bool returnValue = this->doString(luaInput, sourceFileInfo);
127
128        if (sourceFileInfo != NULL)
129        {
130            // Delete source code entry
131            if (sourceFileInfo != NULL)
132                this->sourceCodeMap_.erase(sourceFileInfo->filename);
133        }
134
135        return returnValue;
136    }
137
138    bool LuaState::doFile(const std::string& filename)
139    {
140        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename);
141        if (sourceInfo != NULL)
142            return this->doString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
143        else
144        {
145            COUT(2) << "LuaState: Cannot do file '" << filename << "' (not found)." << std::endl;
146            return false;
147        }
148    }
149
150    bool LuaState::doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
151    {
152        // Save the old source file info
153        shared_ptr<ResourceInfo> oldSourceFileInfo = sourceFileInfo_;
154        // Only override if sourceFileInfo provides useful information
155        if (sourceFileInfo != NULL)
156            sourceFileInfo_ = sourceFileInfo;
157
158        std::string chunkname;
159        if (sourceFileInfo != NULL)
160        {
161            // Provide lua_load with the filename for debug purposes
162            // The '@' is a Lua convention to identify the chunk name as filename
163            chunkname = '@' + sourceFileInfo->filename;
164        }
165        else
166        {
167            // Use the code string to identify the chunk
168            chunkname = code;
169        }
170
171        // Push custom error handler that uses the debugger
172        lua_getglobal(this->luaState_, ERROR_HANDLER_NAME.c_str());
173        int errorHandler = lua_gettop(luaState_);
174        if (lua_isnil(this->luaState_, -1))
175        {
176            lua_pop(this->luaState_, 1);
177            errorHandler = 0;
178        }
179
180        int error = luaL_loadbuffer(luaState_, code.c_str(), code.size(), chunkname.c_str());
181
182        switch (error)
183        {
184        case LUA_ERRSYNTAX: // Syntax error
185            COUT(1) << "Lua syntax error: " << lua_tostring(luaState_, -1) << std::endl;
186            break;
187        case LUA_ERRMEM:    // Memory allocation error
188            COUT(1) << "Lua memory allocation error: Consult your dentist immediately!" << std::endl;
189            break;
190        }
191
192        if (error == 0)
193        {
194            // Execute the chunk in protected mode with an error handler function (stack index)
195            error = lua_pcall(luaState_, 0, 1, errorHandler);
196
197            switch (error)
198            {
199            case LUA_ERRRUN: // Runtime error
200                if (errorHandler)
201                {
202                    // Do nothing (we already display the error in the
203                    // 'errorHandler' Lua function in LuaStateInit.lua)
204                }
205                else
206                {
207                    std::string errorString = lua_tostring(this->luaState_, -1);
208                    if (errorString.find("Error propagation") == std::string::npos)
209                        COUT(1) << "Lua runtime error: " << errorString << std::endl;
210                }
211                break;
212            case LUA_ERRERR: // Error in the error handler
213                COUT(1) << "Lua error in error handler. No message available." << std::endl;
214                break;
215            case LUA_ERRMEM: // Memory allocation error
216                COUT(1) << "Lua memory allocation error: Consult your dentist immediately!" << std::endl;
217                break;
218            }
219        }
220
221        if (error != 0)
222        {
223            lua_pop(luaState_, 1);  // Remove error message
224            lua_pushnil(luaState_); // Push a nil return value
225        }
226
227        if (errorHandler != 0)
228            lua_remove(luaState_, errorHandler); // Remove error handler from stack
229
230        // Set return value to a global variable because we cannot return a table in this function
231        // here. It would work for numbers, pointers and strings, but certainly not for Lua tables.
232        lua_setglobal(luaState_, "LuaStateReturnValue");
233
234        // Load the old info again
235        sourceFileInfo_ = oldSourceFileInfo;
236
237        return (error == 0);
238    }
239
240    void LuaState::luaPrint(const std::string& str)
241    {
242        output_ << str;
243    }
244
245    void LuaState::luaLog(unsigned int level, const std::string& message)
246    {
247        OutputHandler::getOutStream(level) << message << std::endl;
248    }
249
250    bool LuaState::fileExists(const std::string& filename)
251    {
252        shared_ptr<ResourceInfo> info = this->getFileInfo(filename);
253        if (info == NULL)
254            return false;
255        else
256            return true;
257    }
258
259    //! Returns the content of a file
260    std::string LuaState::getSourceCode(const std::string& filename)
261    {
262        // Try the internal map first to get the actual Lua code
263        // and not just some pseudo Lua-XML code when using include* commands
264        std::map<std::string, std::string>::const_iterator it = this->sourceCodeMap_.find(filename);
265        if (it != this->sourceCodeMap_.end())
266            return it->second;
267        shared_ptr<ResourceInfo> info = Resource::getInfo(filename);
268        if (info == NULL)
269            return "";
270        else
271            return Resource::open(info)->getAsString();
272    }
273
274    bool LuaState::usingIOConsole() const
275    {
276        return IOConsole::exists();
277    }
278
279    /*static*/ bool LuaState::addToluaInterface(int (*function)(lua_State*), const std::string& name)
280    {
281        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
282        {
283            if (it->first == name || it->second == function)
284            {
285                COUT(2) << "Warning: Trying to add a Tolua interface with the same name or function." << std::endl;
286                return true;
287            }
288        }
289        toluaInterfaces_s[name] = function;
290
291        // Open interface in all LuaStates
292        for (std::vector<LuaState*>::const_iterator it = instances_s.begin(); it != instances_s.end(); ++it)
293            (*function)((*it)->luaState_);
294
295        // Return dummy bool
296        return true;
297    }
298
299    /*static*/ bool LuaState::removeToluaInterface(const std::string& name)
300    {
301        ToluaInterfaceMap::iterator it = toluaInterfaces_s.find(name);
302        if (it == toluaInterfaces_s.end())
303        {
304            COUT(2) << "Warning: Cannot remove Tolua interface '" << name << "': Not found" << std::endl;
305            return true;
306        }
307
308        // Close interface in all LuaStates
309        for (std::vector<LuaState*>::const_iterator itState = instances_s.begin(); itState != instances_s.end(); ++itState)
310        {
311            lua_pushnil((*itState)->luaState_);
312            lua_setglobal((*itState)->luaState_, it->first.c_str());
313        }
314
315        // Remove entry
316        toluaInterfaces_s.erase(it);
317
318        // Return dummy bool
319        return true;
320    }
321
322    /*static*/ void LuaState::openToluaInterfaces(lua_State* state)
323    {
324        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
325            (*it->second)(state);
326    }
327
328    /*static*/ void LuaState::closeToluaInterfaces(lua_State* state)
329    {
330        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
331        {
332            lua_pushnil(state);
333            lua_setglobal(state, it->first.c_str());
334        }
335    }
336
337
338    LuaFunctor::LuaFunctor(const std::string& code, LuaState* luaState)
339    {
340        this->code_ = code;
341        this->lua_ = luaState;
342    }
343
344    void LuaFunctor::operator()()
345    {
346        lua_->doString(this->code_);
347    }
348}
Note: See TracBrowser for help on using the repository browser.