Files
dl_old/dl/script/dl_as.cpp
T
2024-09-06 19:00:30 +08:00

105 lines
2.6 KiB
C++

#include "dl_as.h"
#include "dl_io.h"
#include <scriptstdstring/scriptstdstring.h>
#include <scriptbuilder/scriptbuilder.h>
#include <scriptstdstring/scriptstdstring.cpp>
#include <scriptbuilder/scriptbuilder.cpp>
namespace dl
{
void as_print(const std::string& msg)
{
log_msg0(msg);
}
void as_message_callback(const asSMessageInfo* msg, void* param)
{
if (msg->type == asMSGTYPE_WARNING)
log_warn("{}({},{}): {}", msg->section, msg->row, msg->col, msg->message);
else if (msg->type == asMSGTYPE_INFORMATION)
log_info("{}({},{}): {}", msg->section, msg->row, msg->col, msg->message);
else
log_err("{}({},{}): {}", msg->section, msg->row, msg->col, msg->message);
}
AngelScript::AngelScript()
{
// 初始化引擎
_engine = asCreateScriptEngine();
if (!_engine)
{
log_err("asCreateScriptEngine 失败!");
return;
}
// 设置消息回调
int r = _engine->SetMessageCallback(asFUNCTION(as_message_callback), 0, asCALL_CDECL);
assert(r >= 0);
// 注册 std::string
RegisterStdString(_engine);
// 注册 print
r = _engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(as_print), asCALL_CDECL); assert(r >= 0);
}
void AngelScript::LoadFile(std::string_view path_name, std::string_view name_module)
{
CScriptBuilder builder;
int r = builder.StartNewModule(_engine, name_module.data());
if (r < 0)
{
log_err("StartNewModule失败!");
return;
}
r = builder.AddSectionFromFile(path_name.data());
if (r < 0)
{
// The builder wasn't able to load the file. Maybe the file
// has been removed, or the wrong name was given, or some
// preprocessing commands are incorrectly written.
log_err("脚本错误!");
return;
}
r = builder.BuildModule();
if (r < 0)
{
// An error occurred. Instruct the script writer to fix the
// compilation errors that were listed in the output stream.
printf("Please correct the errors in the script and try again.\n");
return;
}
}
void AngelScript::Excute(std::string_view name_module)
{
asIScriptModule* mod = _engine->GetModule(name_module.data());
asIScriptFunction* func = mod->GetFunctionByDecl("void main()");
if (func == 0)
{
log_err("脚本需要void main()主函数!");
return;
}
asIScriptContext* ctx = _engine->CreateContext();
ctx->Prepare(func);
int r = ctx->Execute();
if (r != asEXECUTION_FINISHED)
{
// The execution didn't complete as expected. Determine what happened.
if (r == asEXECUTION_EXCEPTION)
{
log_err("脚本出现异常:{}", ctx->GetExceptionString());
}
}
ctx->Release();
}
AngelScript::~AngelScript()
{
_engine->ShutDownAndRelease();
}
}