1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
#include "script_system.h"
#include <iostream>
#include "game.h"
#include "message_system.h"
#include "animation_system.h"
ScriptSystem::ScriptSystem(Game& game) : game_(game) {
engine_.open_libraries(
sol::lib::base,
sol::lib::coroutine,
sol::lib::math);
engine_.new_usertype<MessageSystem>(
"message",
"displayMessage", &MessageSystem::displayMessage,
"hideCutsceneBars", &MessageSystem::hideCutsceneBars,
"isMessageActive", sol::property(&MessageSystem::isMessageActive));
engine_.new_usertype<AnimationSystem>(
"animation",
"setSpriteAnimation", &AnimationSystem::setSpriteAnimation);
engine_.new_usertype<Mixer>(
"mixer",
"playSound", &Mixer::playSound,
"loopSound", &Mixer::loopSound,
"stopChannel", &Mixer::stopChannel);
engine_.set_function(
"message",
[&] () -> MessageSystem& {
return game_.getSystem<MessageSystem>();
});
engine_.set_function(
"animation",
[&] () -> AnimationSystem& {
return game_.getSystem<AnimationSystem>();
});
engine_.set_function(
"mixer",
[&] () -> Mixer& {
return game_.getMixer();
});
engine_.set_function(
"getSpriteByAlias",
[&] (std::string alias) -> int {
return game_.getSpriteByAlias(alias);
});
engine_.set_function(
"loadMap",
[&] (std::string filename, std::string warpPoint) {
game_.loadMap(filename, warpPoint);
});
engine_.script_file("../res/scripts/common.lua");
}
void ScriptSystem::tick(double dt) {
if (callable_ && *callable_) {
auto result = (*callable_)(dt);
if (!result.valid()) {
sol::error e = result;
throw std::runtime_error(e.what());
}
if (!*callable_) {
callable_.reset();
runner_.reset();
}
}
}
void ScriptSystem::runScript(std::string name) {
if (!loadedScripts_.count(name)) {
engine_.script_file("../res/scripts/" + name + ".lua");
loadedScripts_.insert(name);
}
runner_.reset(new sol::thread(sol::thread::create(engine_.lua_state())));
callable_.reset(new sol::coroutine(runner_->state().get<sol::function>(name)));
if (!*callable_) {
throw std::runtime_error("Error running script: " + name);
}
auto result = (*callable_)();
if (!result.valid()) {
sol::error e = result;
throw std::runtime_error(e.what());
}
if (!*callable_) {
callable_.reset();
runner_.reset();
}
}
|