Files
dl_old/dl/script/dl_as.cpp
T
2024-09-29 19:02:56 +08:00

124 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
{
AngelScript* g_as;
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() :
_fileExt{ "as" }
{
// 初始化引擎
_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::Init(std::string_view path, std::string_view file_ext, std::string_view name_prefix)
{
}
void AngelScript::SetPathRoot(std::string_view path)
{
_pathRoot = path;
}
void AngelScript::LoadModule(std::string_view module_name)
{
std::string real_path = fmt::format("{}{}.{}", _pathRoot, module_name, _fileExt);
CScriptBuilder builder;
int r = builder.StartNewModule(_engine, module_name.data());
if (r < 0)
{
log_err("StartNewModule失败!");
return;
}
r = builder.AddSectionFromFile(real_path.data());
if (r < 0)
{
log_err("文件或预处理错误!");
return;
}
r = builder.BuildModule();
if (r < 0)
{
printf("编译错误!");
return;
}
}
void AngelScript::UnloadModule(std::string_view module_name)
{
}
void AngelScript::ExcuteModule(std::string_view module_name)
{
asIScriptModule* mod = _engine->GetModule(module_name.data());
if (!mod)
{
log_err("module不存在:", module_name);
return;
}
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)
{
if (r == asEXECUTION_EXCEPTION)
{
log_err("脚本出现异常:{}", ctx->GetExceptionString());
}
}
ctx->Release();
}
AngelScript::~AngelScript()
{
_engine->ShutDownAndRelease();
}
}