OSDN Git Service

fix cmake/Macros.cmake
[moflib/moflib.git] / moflib-1.0 / src / mof / script / LuaInterpreter.cpp
1 #pragma once
2 #include <mof/script/LuaInterpreter.hpp>
3 #include <mof/script/lua_state.hpp>
4 #include <lua.hpp>
5 #include "luabind/luabind.hpp"
6 #include <mof/ConsoleIO.hpp>
7 #include <mof/utilities.hpp>
8 #include <boost/bind.hpp>
9 #include <list>
10
11 namespace mof
12 {
13 namespace script
14 {
15 //{{{ Impl
16         struct LuaInterpreter::Impl
17         {
18                 std::vector<lua_State*> threads_;
19                 
20                 Impl()
21                 {
22                 }
23
24                 ~Impl()
25                 {
26                 }
27
28         };
29 //}}}
30 //{{{ constructor
31         LuaInterpreter::LuaInterpreter(const mof::tstring& filename)
32         : impl_(new Impl())
33         {
34                 
35                 int error = luaL_dofile(lua_state::instance().raw_lua(), filename.c_str());
36                 if(error)
37                 {
38                         throw std::runtime_error(lua_tostring(lua_state::instance().raw_lua(), -1));
39                 }
40                         
41
42         }
43 //}}}
44 //{{{ destructor
45         LuaInterpreter::~LuaInterpreter()
46         {
47         }
48 //}}}
49 //{{{ update
50         void LuaInterpreter::update()
51         {
52                 foreach (auto& co, impl_->threads_) {
53                         if (!co) continue;// スレッドは既に終了している
54
55                         int error = lua_resume(co, 0);
56                         if (!error) co = NULL;
57                         else if (error != LUA_YIELD) throw std::logic_error(std::string("lua error:") + lua_tostring(co, -1));
58                 }
59         }
60 //}}}
61 //{{{ start
62         void LuaInterpreter::start(const mof::tstring& entry_function)
63         {
64                 lua_State* co = lua_newthread(lua_state::instance().raw_lua());
65                 if(!co)
66                 {
67                         DEBUG_PRINT(_T("ERROR-Failed lua_newthread") );
68                         throw std::runtime_error("Failed --- start lua script");
69                 }
70                 lua_getglobal(co, entry_function.c_str());
71                 impl_->threads_.push_back(co);
72
73         }
74 //}}}
75 //{{{ bind
76         void LuaInterpreter::bind(std::shared_ptr<CommandSet> commands)
77         {
78                 lua_state::instance().bind(commands);
79         }
80 //}}}
81
82 }// namespace script
83 }// namespace mof