scripts are now more error prone
master
Eduardo Bart 13 years ago
parent e611734396
commit 96e0b1e909

@ -6,7 +6,7 @@ SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}")
# find needed packages
SET(Boost_USE_STATIC_LIBS ON)
SET(Boost_USE_MULTITHREADED ON)
FIND_PACKAGE(Boost COMPONENTS system regex signals REQUIRED)
FIND_PACKAGE(Boost COMPONENTS system signals REQUIRED)
FIND_PACKAGE(OpenGL REQUIRED)
FIND_PACKAGE(Lua51 REQUIRED)
FIND_PACKAGE(YamlCpp REQUIRED)

@ -9,7 +9,7 @@ end
function MainMenu_enterGameClicked()
enterGameWindow = loadUI("modules/mainmenu/entergamewindow.yml")
enterGameWindow:getParent():lock(enterGameWindow)
button = enterGameWindow:getChildByID("okButton")
end
function MainMenu_optionsClicked()

@ -54,7 +54,7 @@ bool Configs::load(const std::string& fileName)
m_confsMap[key] = value;
}
} catch (YAML::Exception& e) {
logError("Malformed config file: %s", e.what());
flogError("ERROR: Malformed config file: %s", e.what());
return false;
}
@ -102,7 +102,7 @@ const std::string &Configs::getString(const std::string &key) const
{
auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str());
flogWarning("WARNING: Config value %s not found", key.c_str());
static std::string emptystr;
return emptystr;
}
@ -113,7 +113,7 @@ float Configs::getFloat(const std::string &key) const
{
auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str());
flogWarning("WARNING: Config value %s not found", key.c_str());
return 0;
}
return convertType<float, std::string>(it->second);
@ -123,7 +123,7 @@ bool Configs::getBoolean(const std::string &key) const
{
auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str());
flogWarning("WARNING: Config value %s not found", key.c_str());
return 0;
}
return (it->second == "true");
@ -133,7 +133,7 @@ int Configs::getInteger(const std::string &key) const
{
auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str());
flogWarning("WARNING: Config value %s not found", key.c_str());
return 0;
}
return convertType<int, std::string>(it->second);

@ -41,12 +41,12 @@ void Dispatcher::poll()
}
}
void Dispatcher::scheduleTask(const Callback& callback, int delay)
void Dispatcher::scheduleTask(const SimpleCallback& callback, int delay)
{
m_taskList.push(new Task(g_engine.getCurrentFrameTicks() + delay, callback));
}
void Dispatcher::addTask(const Callback& callback)
void Dispatcher::addTask(const SimpleCallback& callback)
{
m_taskList.push(new Task(callback));
}

@ -29,11 +29,11 @@
class Task {
public:
inline Task(const Callback& _callback) : ticks(0), callback(_callback) { }
inline Task(int _ticks, const Callback& _callback) : ticks(_ticks), callback(_callback) { }
inline Task(const SimpleCallback& _callback) : ticks(0), callback(_callback) { }
inline Task(int _ticks, const SimpleCallback& _callback) : ticks(_ticks), callback(_callback) { }
inline bool operator<(const Task& other) const { return ticks > other.ticks; }
int ticks;
Callback callback;
SimpleCallback callback;
};
class lessTask : public std::binary_function<Task*&, Task*&, bool> {
@ -50,10 +50,10 @@ public:
void poll();
/// Add an event
void addTask(const Callback& callback);
void addTask(const SimpleCallback& callback);
/// Schedula an event
void scheduleTask(const Callback& callback, int delay);
void scheduleTask(const SimpleCallback& callback, int delay);
private:
std::priority_queue<Task*, std::vector<Task*>, lessTask> m_taskList;

@ -87,7 +87,7 @@ void Engine::run()
frameCount = 0;
// update fps text
fpsText = format("FPS: %d", fps);
fpsText = f("FPS: %d", fps);
fpsTextSize = defaultFont->calculateTextRectSize(fpsText);
}
}

@ -63,7 +63,7 @@ public:
/// Return the current ticks on this frame
int getCurrentFrameTicks() const { return m_lastFrameTicks; }
void setOnClose(Callback onCloseCallback) { m_onCloseCallback = onCloseCallback; }
void setOnClose(SimpleCallback onCloseCallback) { m_onCloseCallback = onCloseCallback; }
private:
bool m_stopping;
@ -72,7 +72,7 @@ private:
int m_lastFrameTicks;
Callback m_onCloseCallback;
SimpleCallback m_onCloseCallback;
};
extern Engine g_engine;

@ -44,14 +44,14 @@ bool Resources::setWriteDir(const std::string& path)
bool ret = (bool)PHYSFS_setWriteDir(path.c_str());
if(!ret)
logError("Could not set the path \"%s\" as write directory, file write will not work correctly.", path.c_str());
flogError("ERROR: Could not set the path \"%s\" as write directory, file write will not work correctly.", path.c_str());
return ret;
}
bool Resources::addToSearchPath(const std::string& path, bool insertInFront /*= true*/)
{
if(!PHYSFS_addToSearchPath(path.c_str(), insertInFront ? 0 : 1)) {
logError("Error while adding \"%s\" to resources search path: %s", path.c_str(), PHYSFS_getLastError());
flogError("ERROR: Error while adding \"%s\" to resources search path: %s", path.c_str() % PHYSFS_getLastError());
return false;
}
return true;
@ -66,7 +66,7 @@ uchar *Resources::loadFile(const std::string& fileName, uint *fileSize)
{
PHYSFS_file *file = PHYSFS_openRead(fileName.c_str());
if(!file) {
logError("Failed to load file \"%s\": %s", fileName.c_str(), PHYSFS_getLastError());
flogError("ERROR: Failed to load file \"%s\": %s", fileName.c_str() % PHYSFS_getLastError());
*fileSize = 0;
return NULL;
}
@ -95,7 +95,7 @@ bool Resources::saveFile(const std::string &fileName, const uchar *data, uint si
{
PHYSFS_file *file = PHYSFS_openWrite(fileName.c_str());
if(!file) {
logError("Failed to save file \"%s\": %s", fileName.c_str(), PHYSFS_getLastError());
flogError("ERROR: Failed to save file \"%s\": %s", fileName.c_str() % PHYSFS_getLastError());
return false;
}

@ -68,7 +68,7 @@ bool Font::load(const std::string& file)
{
std::string fileContents = g_resources.loadTextFile(file);
if(!fileContents.size()) {
logError("Coult not load font file \"%s", file.c_str());
flogError("ERROR: Coult not load font file \"%s", file.c_str());
return false;
}
@ -96,7 +96,7 @@ bool Font::load(const std::string& file)
// load texture
m_texture = g_textures.get("fonts/" + textureName);
if(!m_texture) {
logError("Failed to load image for font file \"%s\"", file.c_str());
flogError("ERROR: Failed to load image for font file \"%s\"", file.c_str());
return false;
}
@ -123,7 +123,7 @@ bool Font::load(const std::string& file)
m_glyphHeight);
}
} catch (YAML::Exception& e) {
logError("Malformed font file \"%s\":\n %s", file.c_str(), e.what());
flogError("ERROR: Malformed font file \"%s\":\n %s", file.c_str() % e.what());
return false;
}

@ -47,7 +47,7 @@ void Fonts::init(const std::string& defaultFontName)
}
if(!m_defaultFont)
logFatal("Could not load the default font \"%s\"\n", defaultFontName.c_str());
flogFatal("FATAL ERROR: Could not load the default font \"%s\"\n", defaultFontName.c_str());
}
Font* Fonts::get(const std::string& fontName)
@ -58,6 +58,6 @@ Font* Fonts::get(const std::string& fontName)
return (*it).get();
}
logError("Font \"%s\" not found, returing the default one", fontName.c_str());
flogError("ERROR: Font \"%s\" not found, returing the default one", fontName.c_str());
return m_defaultFont.get();
}

@ -43,8 +43,8 @@ void Graphics::init()
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
logInfo("GPU %s", (const char*)glGetString(GL_RENDERER));
logInfo("OpenGL %s", (const char*)glGetString(GL_VERSION));
flogInfo("GPU %s", (const char*)glGetString(GL_RENDERER));
flogInfo("OpenGL %s", (const char*)glGetString(GL_VERSION));
}
void Graphics::terminate()

@ -46,18 +46,18 @@ TexturePtr Textures::get(const std::string& textureFile)
if(!texture) {
// currently only png textures are supported
if(!boost::ends_with(textureFile, ".png"))
logFatal("Unable to load texture %s, file format no supported.", textureFile.c_str());
flogFatal("FATAL ERROR: Unable to load texture %s, file format no supported.", textureFile.c_str());
// load texture file data
uint fileSize;
uchar *textureFileData = g_resources.loadFile(textureFile, &fileSize);
if(!textureFileData)
logFatal("Unable to load texture %s, file could not be read.", textureFile.c_str());
flogFatal("FATAL ERROR: Unable to load texture %s, file could not be read.", textureFile.c_str());
// load the texture
texture = TexturePtr(TextureLoader::loadPNG(textureFileData));
if(!texture)
logFatal("Unable to load texture %s", textureFile.c_str());
flogFatal("FATAL ERROR: Unable to load texture %s", textureFile.c_str());
delete[] textureFileData;
}

@ -40,7 +40,7 @@ void Connection::poll()
ioService.reset();
}
void Connection::connect(const std::string& host, uint16 port, const Callback& callback)
void Connection::connect(const std::string& host, uint16 port, const SimpleCallback& callback)
{
m_connectCallback = callback;
m_connectionState = CONNECTION_STATE_RESOLVING;

@ -37,7 +37,7 @@ public:
static void poll();
void connect(const std::string& host, uint16 port, const Callback& callback);
void connect(const std::string& host, uint16 port, const SimpleCallback& callback);
void setErrorCallback(const ErrorCallback& errorCallback) { m_errorCallback = errorCallback; }
void onTimeout(const boost::system::error_code& error);
@ -53,7 +53,7 @@ public:
private:
ErrorCallback m_errorCallback;
Callback m_connectCallback;
SimpleCallback m_connectCallback;
ConnectionState_t m_connectionState;
boost::asio::deadline_timer m_timer;

@ -30,14 +30,14 @@ Protocol::Protocol() :
m_connection->setErrorCallback(boost::bind(&Protocol::onError, this, _1));
}
void Protocol::connect(const std::string& host, uint16 port, const Callback& callback)
void Protocol::connect(const std::string& host, uint16 port, const SimpleCallback& callback)
{
m_connection->connect(host, port, callback);
}
void Protocol::onError(const boost::system::error_code& error)
{
logError(error.message().c_str());
flogError("PROTOCOL ERROR: ", error.message());
// invalid hostname
// connection timeouted

@ -32,7 +32,7 @@ class Protocol
public:
Protocol();
void connect(const std::string& host, uint16 port, const Callback& callback);
void connect(const std::string& host, uint16 port, const SimpleCallback& callback);
virtual void onError(const boost::system::error_code& error);

@ -211,7 +211,7 @@ void Platform::init(const char *appName)
wc.lpszClassName = win32.appName.c_str(); // Set The Class Name
if(!RegisterClassA(&wc))
logFatal("Failed to register the window class.");
logFatal("FATAL ERROR: Failed to register the window class.");
// force first tick
Platform::getTicks();
@ -226,7 +226,7 @@ void Platform::terminate()
if(win32.instance) {
if(!UnregisterClassA(win32.appName.c_str(), win32.instance))
logError("Unregister class failed.");
logError("ERROR: Unregister class failed.");
win32.instance = NULL;
}
@ -286,7 +286,7 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
if(!win32.window) {
terminate();
logFatal("Window creation error.");
logFatal("FATAL ERROR: Window creation error.");
return false;
}
@ -315,31 +315,31 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
if(!(win32.hdc = GetDC(win32.window))) {
terminate();
logFatal("Can't Create A GL Device Context.");
logFatal("FATAL ERROR: Can't Create A GL Device Context.");
return false;
}
if(!(pixelFormat = ChoosePixelFormat(win32.hdc, &pfd))) {
terminate();
logFatal("Can't Find A Suitable PixelFormat.");
logFatal("FATAL ERROR: Can't Find A Suitable PixelFormat.");
return false;
}
if(!SetPixelFormat(win32.hdc, pixelFormat, &pfd)) {
terminate();
logFatal("Can't Set The PixelFormat.");
logFatal("FATAL ERROR: Can't Set The PixelFormat.");
return false;
}
if(!(win32.hrc = wglCreateContext(win32.hdc))) {
terminate();
logFatal("Can't Create A GL Rendering Context.");
logFatal("FATAL ERROR: Can't Create A GL Rendering Context.");
return false;
}
if(!wglMakeCurrent(win32.hdc, win32.hrc)) {
terminate();
logFatal("Can't Activate The GL Rendering Context.");
logFatal("FATAL ERROR: Can't Activate The GL Rendering Context.");
return false;
}
@ -350,24 +350,24 @@ void Platform::destroyWindow()
{
if(win32.hrc) {
if(!wglMakeCurrent(NULL, NULL))
logError("Release Of DC And RC Failed.");
logError("ERROR: Release Of DC And RC Failed.");
if(!wglDeleteContext(win32.hrc))
logError("Release Rendering Context Failed.");
logError("ERROR: Release Rendering Context Failed.");
win32.hrc = NULL;
}
if(win32.hdc) {
if(!ReleaseDC(win32.window, win32.hdc))
logError("Release Device Context Failed.");
logError("ERROR: Release Device Context Failed.");
win32.hdc = NULL;
}
if(win32.window) {
if(!DestroyWindow(win32.window))
logError("Destroy window failed.");
logError("ERROR: Destroy window failed.");
win32.window = NULL;
}
@ -502,7 +502,7 @@ std::string Platform::getAppUserDir()
std::stringstream sdir;
sdir << PHYSFS_getUserDir() << "/." << win32.appName << "/";
if((mkdir(sdir.str().c_str()) != 0) && (errno != EEXIST))
logError("Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str());
logError("ERROR: Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str());
return sdir.str();
}

@ -234,18 +234,18 @@ void Platform::init(const char *appName)
// open display
x11.display = XOpenDisplay(0);
if(!x11.display)
logFatal("Failed to open X display");
logFatal("FATAL ERROR: Failed to open X display");
// check if GLX is supported on this display
if(!glXQueryExtension(x11.display, 0, 0))
logFatal("GLX not supported");
logFatal("FATAL ERROR: GLX not supported");
// retrieve GLX version
int glxMajor;
int glxMinor;
if(!glXQueryVersion(x11.display, &glxMajor, &glxMinor))
logFatal("Unable to query GLX version");
logInfo("GLX version %d.%d", glxMajor, glxMinor);
logFatal("FATAL ERROR: Unable to query GLX version");
flogInfo("GLX version %d.%d", glxMajor % glxMinor);
// clipboard related atoms
x11.atomClipboard = XInternAtom(x11.display, "CLIPBOARD", False);
@ -497,12 +497,12 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
// choose OpenGL, RGBA, double buffered, visual
x11.visual = glXChooseVisual(x11.display, DefaultScreen(x11.display), attrList);
if(!x11.visual)
logFatal("RGBA/Double buffered visual not supported");
logFatal("FATAL ERROR: RGBA/Double buffered visual not supported");
// create GLX context
x11.glxContext = glXCreateContext(x11.display, x11.visual, 0, GL_TRUE);
if(!x11.glxContext)
logFatal("Unable to create GLX context");
logFatal("FATAL ERROR: Unable to create GLX context");
// color map
x11.colormap = XCreateColormap(x11.display,
@ -535,7 +535,7 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
&wa);
if(!x11.window)
logFatal("Unable to create X window");
logFatal("FATAL ERROR: Unable to create X window");
// create input context (to have better key input handling)
if(XSupportsLocale()) {
@ -547,11 +547,11 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, x11.window, NULL);
if(!x11.xic)
logError("Unable to create the input context");
logError("ERROR: Unable to create the input context");
} else
logError("Failed to open an input method");
logError("ERROR: Failed to open an input method");
} else
logError("X11 does not support the current locale");
logError("ERROR: X11 does not support the current locale");
if(!x11.xic)
logWarning("Input of special keys maybe messed up because we couldn't create an input context");
@ -836,6 +836,6 @@ std::string Platform::getAppUserDir()
std::stringstream sdir;
sdir << PHYSFS_getUserDir() << "/." << x11.appName << "/";
if((mkdir(sdir.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) && (errno != EEXIST))
logError("Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str());
flogError("ERROR: Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str());
return sdir.str();
}

@ -62,7 +62,6 @@ typedef int8_t int8;
// boost utilities
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
@ -72,7 +71,7 @@ typedef int8_t int8;
#include <boost/signals.hpp>
#define foreach BOOST_FOREACH
typedef boost::function<void()> Callback;
typedef boost::function<void()> SimpleCallback;
// yaml
#include <yaml-cpp/yaml.h>

@ -61,12 +61,19 @@ int LuaScript::lua_loadUI()
{
UIContainerPtr parent;
if(getStackSize() > 1) {
parent = boost::static_pointer_cast<UIContainer>(popClassInstance());
parent = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
} else {
parent = UIContainer::getRootContainer();
}
std::string uiFile = popString();
UIElementPtr element = UILoader::loadFile(uiFile.c_str(), parent);
UIElementPtr element;
if(parent)
element = UILoader::loadFile(uiFile.c_str(), parent);
else
reportErrorWithTraceback("invalid parent container");
pushClassInstance(element);
return 1;
}
@ -78,7 +85,6 @@ int LuaScript::lua_getUIRootContainer()
return 1;
}
int LuaScript::lua_setOnApplicationClose()
{
int funcRef = popFunction();
@ -91,7 +97,7 @@ int LuaScript::lua_setOnApplicationClose()
int LuaScript::lua_UIElement_destroy()
{
UIElementPtr element = boost::static_pointer_cast<UIElement>(popClassInstance());
UIElementPtr element = boost::dynamic_pointer_cast<UIElement>(popClassInstance());
if(element)
element->destroy();
else
@ -101,7 +107,7 @@ int LuaScript::lua_UIElement_destroy()
int LuaScript::lua_UIElement_getParent()
{
UIElementPtr element = boost::static_pointer_cast<UIElement>(popClassInstance());
UIElementPtr element = boost::dynamic_pointer_cast<UIElement>(popClassInstance());
if(element)
pushClassInstance(element->getParent());
else
@ -111,13 +117,13 @@ int LuaScript::lua_UIElement_getParent()
int LuaScript::lua_UIButton_setOnClick()
{
lua_insert(L, -2);
UIButtonPtr button = boost::static_pointer_cast<UIButton>(popClassInstance());
moveTop(-2);
UIButtonPtr button = boost::dynamic_pointer_cast<UIButton>(popClassInstance());
if(button) {
int funcRef = popFunction();
button->setOnClick([this, funcRef](UIButtonPtr button) {
pushFunction(funcRef);
setSelf(button);
setLocal(button, "self");
callFunction();
});
} else {
@ -129,7 +135,7 @@ int LuaScript::lua_UIButton_setOnClick()
int LuaScript::lua_UIContainer_getChildByID()
{
std::string id = popString();
UIContainerPtr container = boost::static_pointer_cast<UIContainer>(popClassInstance());
UIContainerPtr container = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
if(container)
pushClassInstance(container->getChildById(id));
else
@ -139,9 +145,14 @@ int LuaScript::lua_UIContainer_getChildByID()
int LuaScript::lua_UIContainer_lock()
{
UIElementPtr element = boost::static_pointer_cast<UIElement>(popClassInstance());
UIContainerPtr container = boost::static_pointer_cast<UIContainer>(popClassInstance());
if(container && element) {
UIElementPtr element = boost::dynamic_pointer_cast<UIElement>(popClassInstance());
UIContainerPtr container = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
if(!element) {
reportFuncErrorWithTraceback("invalid lock element");
return 1;
}
if(container) {
container->lockElement(element);
}
return 1;
@ -149,7 +160,7 @@ int LuaScript::lua_UIContainer_lock()
int LuaScript::lua_UIContainer_unlock()
{
UIContainerPtr container = boost::static_pointer_cast<UIContainer>(popClassInstance());
UIContainerPtr container = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
if(container) {
container->unlockElement();
}

@ -32,7 +32,7 @@ LuaScript::LuaScript()
{
L = luaL_newstate();
if(!L)
logFatal("could not create lua context");
logFatal("FATAL ERROR: could not create lua context");
// load lua standard libraries
luaL_openlibs(L);
@ -64,7 +64,7 @@ void LuaScript::loadAllModules()
bool LuaScript::loadFile(const std::string& fileName)
{
if(!g_resources.fileExists(fileName)) {
logError("script file '%s' doesn't exist", fileName.c_str());
flogError("ERROR: script file '%s' doesn't exist", fileName.c_str());
return false;
}
std::string fileContents = g_resources.loadTextFile(fileName);
@ -114,11 +114,18 @@ int LuaScript::loadBufferAsFunction(const std::string& text, const std::string&
void LuaScript::reportError(const std::string& errorDesc, const char *funcName)
{
std::stringstream ss;
ss << "LUA script error";
ss << "LUA Script ERROR: ";
if(funcName)
ss << " in " << funcName << "()";
ss << ": " << errorDesc << std::endl;
logError(ss.str().c_str());
ss << " in " << funcName << "(): ";
ss << errorDesc << std::endl;
logError(ss.str());
}
void LuaScript::reportErrorWithTraceback(const std::string& errorDesc, const char* funcName)
{
pushString(errorDesc);
luaErrorHandler(L);
reportError(popString(), funcName);
}
int LuaScript::getStackSize()
@ -126,6 +133,11 @@ int LuaScript::getStackSize()
return lua_gettop(L);
}
void LuaScript::moveTop(int index)
{
lua_insert(L, index);
}
void LuaScript::pop(int n)
{
lua_pop(L, n);
@ -141,15 +153,15 @@ bool LuaScript::popBoolean()
int32_t LuaScript::popInteger()
{
double d = lua_tonumber(L, -1);
pop(1);
pop();
return (int)d;
}
std::string LuaScript::popString()
{
size_t len;
const char *cstr = lua_tolstring(L, -1, &len);
std::string str(cstr, len);
std::string str;
if(lua_isstring(L, -1))
str = lua_tostring(L, -1);
pop();
return str;
}
@ -181,8 +193,10 @@ void LuaScript::pushUserdata(void* ptr)
void LuaScript::pushClassInstance(const ScriptablePtr& object)
{
if(object && object->getScriptableName()) {
if(object) {
// create weak_ptr to the scriptable object stored as userdata
new(lua_newuserdata(L, sizeof(ScriptableWeakPtr))) ScriptableWeakPtr(object);
// set object metatable
lua_getfield(L, LUA_REGISTRYINDEX, (std::string(object->getScriptableName()) + "_mt").c_str());
lua_setmetatable(L, -2);
} else {
@ -192,18 +206,14 @@ void LuaScript::pushClassInstance(const ScriptablePtr& object)
ScriptablePtr LuaScript::popClassInstance()
{
if(!lua_isuserdata(L, -1)) {
reportError(format("couldn't pop a class instance, top objet is not a valid type (%s)", luaL_typename(L, -1)));
lua_pop(L, 1);
return ScriptablePtr();
}
ScriptableWeakPtr *objectRef = (ScriptableWeakPtr *)lua_touserdata(L, -1);
ScriptablePtr object;
if(lua_isuserdata(L, -1)) { // instances are store as userdata
object = ((ScriptableWeakPtr *)lua_touserdata(L, -1))->lock();
if(!object)
reportErrorWithTraceback("attempt to retrive class instance from a object that is already expired");
} else if(!lua_isnil(L, -1)) // we accept nil values
reportErrorWithTraceback("couldn't retrive class instance, the value is not a scriptable type");
lua_pop(L, 1);
ScriptablePtr object = objectRef->lock();
if(!object)
reportError(format("attempt to retrive class instance from a object that is already expired"));
return object;
}
@ -240,11 +250,11 @@ void LuaScript::callFunction(int numArgs)
reportError("stack size changed!");
}
void LuaScript::setSelf(const ScriptablePtr& scriptable, int envIndex)
void LuaScript::setLocal(const ScriptablePtr& scriptable, const char *varName, int envIndex)
{
lua_getfenv(L, envIndex);
pushClassInstance(scriptable);
lua_setfield(L, -2, "self");
lua_setfield(L, -2, varName);
lua_pop(L, 1);
}
@ -382,24 +392,36 @@ int LuaScript::luaCompareClassInstances(lua_State* L)
int LuaScript::luaFunctionCallback(lua_State* L)
{
// look for function id
int id = lua_tonumber(L, lua_upvalueindex(1));
// call the function
return (g_lua.*(g_lua.m_functions[id]))();
}
int LuaScript::luaErrorHandler(lua_State *L)
{
// push debug
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if(!lua_istable(L, -1)) {
lua_pop(L, 1);
return 1;
}
// push debug.traceback
lua_getfield(L, -1, "traceback");
if(!lua_isfunction(L, -1)) {
lua_pop(L, 2);
return 1;
}
lua_pushvalue(L, 1);
// remove debug
lua_remove(L, -2);
// push additional error message
lua_pushvalue(L, -2);
// push level
lua_pushinteger(L, 2);
// call debug.traceback
lua_call(L, 2, 1);
// remove additional error message
lua_remove(L, -2);
// return, the complete error message is on the stack
return 1;
}

@ -30,6 +30,7 @@
#include <lua.hpp>
#define reportFuncError(a) reportError(a, __FUNCTION__)
#define reportFuncErrorWithTraceback(a) reportErrorWithTraceback(a, __FUNCTION__)
class LuaScript
{
@ -42,8 +43,10 @@ public:
bool loadBuffer(const std::string& text, const std::string& what = "luaBuffer");
int loadBufferAsFunction(const std::string& text, const std::string& what = "luaBuffer");
void reportError(const std::string& errorDesc, const char *funcName = NULL);
void reportErrorWithTraceback(const std::string& errorDesc, const char *funcName = NULL);
int getStackSize();
void moveTop(int index);
void pushNil();
void pushBoolean(bool b);
@ -61,7 +64,7 @@ public:
void releaseFunction(int functionRef);
void callFunction(int numArgs = 0);
void setSelf(const ScriptablePtr& scriptable, int envIndex = -1);
void setLocal(const ScriptablePtr& scriptable, const char *varName, int envIndex = -1);
void pushClassInstance(const ScriptablePtr& object);
ScriptablePtr popClassInstance();

@ -47,7 +47,7 @@ int AnchorLine::getPos() const
return 0;
}
}
logError("anchor line of an element has expired, your UI is missconfigured");
logError("ERROR: anchor line of an element has expired, your UI is missconfigured");
return 0;
}
@ -74,7 +74,7 @@ bool UILayout::addAnchor(EAnchorType type, const AnchorLine& anchorLine)
{
// we can never anchor with itself
if(anchorLine.getRelativeElement() == asUILayout()) {
logError("anchoring with itself is not possible");
logError("ERROR: anchoring with itself is not possible");
return false;
}
@ -82,7 +82,7 @@ bool UILayout::addAnchor(EAnchorType type, const AnchorLine& anchorLine)
// this only happens in missconfigurations
for(auto it = m_anchoredElements.begin(); it != m_anchoredElements.end(); ++it) {
if((*it).lock() == anchorLine.getRelativeElement()) {
logError("anchoring elements with each other is not possible");
logError("ERROR: anchoring elements with each other is not possible");
return false;
}
}

@ -67,7 +67,7 @@ UIElementPtr UILoader::loadFile(const std::string& file, const UIContainerPtr& p
{
std::string fileContents = g_resources.loadTextFile(file);
if(!fileContents.size()) {
logError("Could not load ui file \"%s", file.c_str());
flogError("ERROR: Could not load ui file \"%s", file.c_str());
return UIElementPtr();
}
@ -101,7 +101,7 @@ UIElementPtr UILoader::loadFile(const std::string& file, const UIContainerPtr& p
return element;
} catch (YAML::Exception& e) {
logError("Failed to load ui file \"%s\":\n %s", file.c_str(), e.what());
flogError("ERROR: Failed to load ui file \"%s\":\n %s", file.c_str() % e.what());
}
return UIElementPtr();

@ -38,7 +38,7 @@ void UISkins::load(const std::string& skinsFile)
{
std::string fileContents = g_resources.loadTextFile(skinsFile);
if(!fileContents.size())
logFatal("Could not load skin file \"%s", skinsFile.c_str());
flogFatal("FATAL ERROR: Could not load skin file \"%s", skinsFile.c_str());
std::istringstream fin(fileContents);
@ -126,7 +126,7 @@ void UISkins::load(const std::string& skinsFile)
}
}
} catch (YAML::Exception& e) {
logFatal("Malformed skin file \"%s\":\n %s", skinsFile.c_str(), e.what());
flogFatal("FATAL ERROR: Malformed skin file \"%s\":\n %s", skinsFile.c_str() % e.what());
}
}
@ -143,6 +143,6 @@ UIElementSkinPtr UISkins::getElementSkin(UI::EElementType elementType, const std
if(elementType == skin->getElementType() && name == skin->getName())
return skin;
}
logWarning("Element skin '%s' not found", name.c_str());
flogWarning("Element skin '%s' not found", name.c_str());
return UIElementSkinPtr();
}

@ -26,17 +26,10 @@
#include <iostream>
#include <cstdlib>
#include <stdarg.h>
void Logger::_log(int level, const char *trace, const char *format, ...)
void Logger::log(int level, const std::string& text, const char *trace)
{
va_list args;
std::string strace;
va_start(args, format);
std::string text = vformat(format, args);
va_end(args);
if(trace) {
strace = trace;
strace = strace.substr(0, strace.find_first_of('('));
@ -54,8 +47,6 @@ void Logger::_log(int level, const char *trace, const char *format, ...)
if(!strace.empty())
std::cout << "[" << strace << "] ";
static char const *prefixes[] = { "FATAL ERROR: ", "ERROR: ", "WARNING: ", "", "", "" };
std::cout << prefixes[level];
std::cout << text;
#ifdef linux
@ -68,3 +59,4 @@ void Logger::_log(int level, const char *trace, const char *format, ...)
if(level == LFATAL)
exit(-1);
}

@ -26,33 +26,39 @@
#define LOGGER_H
#include <sstream>
#include <boost/format.hpp>
namespace Logger {
class Logger {
public:
enum ELogLevel {
LFATAL = 0,
LERROR,
LWARNING,
LINFO,
LDEBUG
};
enum ELogLevel {
LFATAL = 0,
LERROR,
LWARNING,
LINFO,
LDEBUG
static void log(int level, const std::string& text = "", const char *trace = NULL);
};
void _log(int level, const char *trace, const char *format, ...);
}
#define logFatal(a) Logger::log(Logger::LFATAL, a)
#define logError(a) Logger::log(Logger::LERROR, a)
#define logWarning(a) Logger::log(Logger::LWARNING, a)
#define logDebug(a) Logger::log(Logger::LDEBUG, a)
#define logInfo(a) Logger::log(Logger::LINFO, a)
#define logFatal(...) Logger::_log(Logger::LFATAL, NULL, __VA_ARGS__)
#define logError(...) Logger::_log(Logger::LERROR, NULL, __VA_ARGS__)
#define logWarning(...) Logger::_log(Logger::LWARNING, NULL, __VA_ARGS__)
#define logDebug(...) Logger::_log(Logger::LDEBUG, NULL, __VA_ARGS__)
#define logInfo(...) Logger::_log(Logger::LINFO, NULL, __VA_ARGS__)
#define flogFatal(a,b) Logger::log(Logger::LFATAL, (boost::format(a) % b).str())
#define flogError(a,b) Logger::log(Logger::LERROR, (boost::format(a) % b).str())
#define flogWarning(a,b) Logger::log(Logger::LWARNING, (boost::format(a) % b).str())
#define flogDebug(a,b) Logger::log(Logger::LDEBUG, (boost::format(a) % b).str())
#define flogInfo(a,b) Logger::log(Logger::LINFO, (boost::format(a) % b).str())
#define logTrace() Logger::_log(Logger::LDEBUG, __PRETTY_FUNCTION__, "")
#define logTraceFatal(...) Logger::_log(Logger::LFATAL, __PRETTY_FUNCTION__, __VA_ARGS__)
#define logTraceError(...) Logger::_log(Logger::LERROR, __PRETTY_FUNCTION__, __VA_ARGS__)
#define logTraceWarning(...) Logger::_log(Logger::LWARNING, __PRETTY_FUNCTION__, __VA_ARGS__)
#define logTraceDebug(...) Logger::_log(Logger::LDEBUG, __PRETTY_FUNCTION__, __VA_ARGS__)
#define logTraceInfo(...) Logger::_log(Logger::LINFO, __PRETTY_FUNCTION__, __VA_ARGS__)
#define logTrace() Logger::log(Logger::LDEBUG, "", __PRETTY_FUNCTION__)
#define logTraceFatal(a) Logger::log(Logger::LFATAL, a, __PRETTY_FUNCTION__)
#define logTraceError(a) Logger::log(Logger::LERROR, a, __PRETTY_FUNCTION__)
#define logTraceWarning(a) Logger::log(Logger::LWARNING, a, __PRETTY_FUNCTION__)
#define logTraceDebug(a) Logger::log(Logger::LDEBUG, a, __PRETTY_FUNCTION__)
#define logTraceInfo(a) Logger::log(Logger::LINFO, a, __PRETTY_FUNCTION__)
struct Dump {
public:
@ -65,4 +71,4 @@ private:
#define dump Dump()
#endif
#endif // LOGGER_H

@ -23,30 +23,3 @@
#include <util/util.h>
#include <cstdio>
std::string vformat(const char *format, va_list args)
{
if(!format)
return "";
int result = -1, length = 256;
char *buffer = 0;
while(result == -1) {
if(buffer)
delete [] buffer;
buffer = new char [length + 1];
result = vsnprintf(buffer, length, format, args);
length *= 2;
}
std::string s(buffer);
delete [] buffer;
return s;
}
std::string format(const char *format, ...)
{
va_list args;
va_start(args, format);
std::string s = vformat(format, args);
va_end(args);
return s;
}

@ -26,14 +26,11 @@
#define UTIL_H
#include <util/logger.h>
#include <stdarg.h>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
/// Formatting like printf for std::string, va_list input version
std::string vformat(const char *format, va_list args);
/// Formatting like printf for std::string
std::string format(const char *format, ...);
/// Easy/fast writting formater
#define f(a, b) (boost::format(a) % b).str()
/// Convert any data type through boost::lexical_cast
template<class R, class T>
@ -43,9 +40,9 @@ R convertType(T t)
try {
ret = boost::lexical_cast<R>(t);
} catch(boost::bad_lexical_cast bad) {
logError("Error converting type: %s", bad.what());
flogError("Error converting type: %s", bad.what());
}
return ret;
}
#endif
#endif // UTIL_H

@ -121,7 +121,7 @@ int main(int argc, const char *argv[])
g_lua.loadAllModules();
if(!UIContainer::getRootContainer()->getChildCount())
logFatal("no ui loaded at all, no reason to continue running");
logFatal("FATAL ERROR: no ui loaded at all, no reason to continue running");
Platform::showWindow();
//Platform::hideMouseCursor();

Loading…
Cancel
Save