Posted on 2008-12-14 21:33
Condor 閱讀(1503)
評論(0) 編輯 收藏 引用
可能是還在開發當中的緣故, 我感覺Nebula3中的lua腳本系統不是很完善. 所有的調用都是封裝成Command來執行的, 并不像LuaBind那樣直接綁定到C++類對象; 而且, 對于C++調用腳本的接口也不是很方便, 只有一個Eval()來執行一個字符串. 如果要實際進行應用的話, 我想最好是自己擴展一下, 這里有一篇不錯的文章: Integrating Lua into C++. 當然, 對于需求更高的用戶來說, 可以選擇使用LuaBind等第三方庫來整合腳本系統.
Command(命令)
可以這么說, 腳本中調用的, 都是一個個的Command. 一個新的Command定義了一個腳本語言獨立的新的腳本命令, 你可以通過派生一個Command的子類并注冊到腳本服務器來實現. 也就是說, 新的命令不依賴于你具體使用的腳本系統, 可以是lua, 也可以是python等等.
view plaincopy to clipboardprint?
- class Print : public Scripting::Command
- {
- DeclareClass(Print);
- public:
- virtual void OnRegister();
- virtual bool OnExecute();
- virtual Util::String GetHelp() const;
- private:
- void Callback(const Util::String& str);
- };<PRE></PRE>
class Print : public Scripting::Command
{
DeclareClass(Print);
public:
virtual void OnRegister();
virtual bool OnExecute();
virtual Util::String GetHelp() const;
private:
void Callback(const Util::String& str);
};
ScriptServer(腳本服務器)
ScriptServer是語言無雙的, 也就是說你可以自己派生一個相應語言的子來來支持一種腳本言. Nebula3里已經實現了一個LuaServer, 不過個感覺沒有LuaBind方便. 所有的腳本執行都是通過LuaServer::Eval(const String& str)來完成的. 腳本要調用C++代碼的話, 需要封裝一個Command, 然后用LuaServer::RegisterCommand()來注冊就可以用了. 具體可以參考Command命名空間里的相關代碼.
view plaincopy to clipboardprint?
- scriptServer->RegisterCommand("print", Print::Create());<PRE></PRE>
scriptServer->RegisterCommand("print", Print::Create());
應用實例
其實App::ConsoleApplication里就有LuaServer, 并且已經注冊了一些IO命名. 我們派生一個從命令行讀取腳本命令執行的來做測試:
view plaincopy to clipboardprint?
- class ScripTestApp : public App::ConsoleApplication
- {
- public:
- ScripTestApp(void);
-
- /// open the application
- virtual bool Open();
- /// run the application, return when user wants to exit
- virtual void Run();
- };
-
- ScripTestApp::ScripTestApp(void)
- {
- }
-
- bool ScripTestApp::Open()
- {
- if (ConsoleApplication::Open())
- {
- return true;
- }
- return false;
- }
-
- void ScripTestApp::Run()
- {
- Util::String input;
- while (true)
- {
- input = IO::Console::Instance()->GetInput();
- if (!input.IsEmpty())
- {
- this->scriptServer->Eval(input);
- }
- }
- }<PRE></PRE>
class ScripTestApp : public App::ConsoleApplication
{
public:
ScripTestApp(void);
/// open the application
virtual bool Open();
/// run the application, return when user wants to exit
virtual void Run();
};
ScripTestApp::ScripTestApp(void)
{
}
bool ScripTestApp::Open()
{
if (ConsoleApplication::Open())
{
return true;
}
return false;
}
void ScripTestApp::Run()
{
Util::String input;
while (true)
{
input = IO::Console::Instance()->GetInput();
if (!input.IsEmpty())
{
this->scriptServer->Eval(input);
}
}
}
運行結果:
