From 6c3f324affafac14897776d0fdf4732dde69eae5 Mon Sep 17 00:00:00 2001 From: Nick Gasson Date: Sun, 6 Jun 2010 19:01:36 +0100 Subject: [PATCH] Load Lua script when playing game --- include/ILua.hpp | 1 + scripts/trading.lua | 2 ++ src/Game.cpp | 4 ++++ src/LuaWrap.cpp | 46 +++++++++++++++++++++++++++++++++++++-------- 4 files changed, 45 insertions(+), 8 deletions(-) create mode 100644 scripts/trading.lua diff --git a/include/ILua.hpp b/include/ILua.hpp index df1710a..c86756b 100644 --- a/include/ILua.hpp +++ b/include/ILua.hpp @@ -25,6 +25,7 @@ struct ILua { virtual ~ILua() {} virtual void eval(const string& code) = 0; + virtual void loadFile(const string& file) = 0; }; typedef shared_ptr ILuaPtr; diff --git a/scripts/trading.lua b/scripts/trading.lua new file mode 100644 index 0000000..48c1d6a --- /dev/null +++ b/scripts/trading.lua @@ -0,0 +1,2 @@ +debug("Hello from Lua!") + diff --git a/src/Game.cpp b/src/Game.cpp index 0c943dc..f091a74 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -27,6 +27,7 @@ #include "IterateTrack.hpp" #include "IConfig.hpp" #include "IMessageArea.hpp" +#include "ILua.hpp" #include "gui/ILayout.hpp" #include "gui/Label.hpp" @@ -97,6 +98,9 @@ Game::Game(IMapPtr aMap) layout = gui::makeLayout("layouts/game.xml"); messageArea = makeMessageArea(); + // Load the logic script + getLua()->loadFile("scripts/trading.lua"); + switchToBirdCamera(); } diff --git a/src/LuaWrap.cpp b/src/LuaWrap.cpp index 6b27bf2..078c9f8 100644 --- a/src/LuaWrap.cpp +++ b/src/LuaWrap.cpp @@ -51,7 +51,10 @@ public: ~LuaWrap(); void eval(const string& code); + void loadFile(const string& file); private: + void pcall(); + lua_State* luaVM; }; @@ -72,6 +75,22 @@ LuaWrap::~LuaWrap() lua_close(luaVM); } +void LuaWrap::pcall() +{ + int result = lua_pcall(luaVM, 0, 0, 0); + + switch (result) { + case LUA_ERRRUN: + case LUA_ERRERR: + error() << "Lua: " << lua_tolstring(luaVM, -1, NULL); + lua_pop(luaVM, 1); + break; + case LUA_ERRMEM: + error() << "Lua out of memory!"; + break; + } +} + void LuaWrap::eval(const string& code) { int result = luaL_loadstring(luaVM, code.c_str()); @@ -85,17 +104,28 @@ void LuaWrap::eval(const string& code) return; } - result = lua_pcall(luaVM, 0, 0, 0); + pcall(); +} + +void LuaWrap::loadFile(const string& file) +{ + log() << "Loading Lua script " << file; + + int result = luaL_loadfile(luaVM, file.c_str()); + switch (result) { - case LUA_ERRRUN: - case LUA_ERRERR: - error() << "Lua: " << lua_tolstring(luaVM, -1, NULL); - lua_pop(luaVM, 1); - break; + case LUA_ERRSYNTAX: + error() << "Lua syntax error"; + return; case LUA_ERRMEM: - error() << "Lua out of memory!"; - break; + error() << "Out of Lua memory"; + return; + case LUA_ERRFILE: + error() << "Failed to open file: " << file; + return; } + + pcall(); } ILuaPtr getLua() -- 2.39.2