/****************************************************************************** * File - wren_state.cpp * Author - Joey Pollack * Date - 2022/10/25 (y/m/d) * Mod Date - 2022/10/25 (y/m/d) * Description - Manages the wren vm, runs scripts. This is the main * interface for wren. ******************************************************************************/ #include "wren_state.h" #include "wren_script.h" #include #include namespace lunarium { WrenState::~WrenState() { Shutdown(); } void WrenState::Shutdown() { wrenFreeVM(mpVM); mpVM = nullptr; } u32 WrenState::mLogCat = Logger::RegisterCategory("SCRIPT"); OpRes WrenState::Initialize() { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = WrenState::WriteFN; config.errorFn = WrenState::ErrorFN; mpVM = wrenNewVM(&config); return OpRes::OK(); } u32 WrenState::GetLogCat() const { return mLogCat; } void WrenState::RunScript(WrenScript* script) { if (!mpVM) { Logger::Error(mLogCat, "Could not run script - the VM is nullptr"); return; } WrenInterpretResult result = wrenInterpret(mpVM, script->GetModuleName().c_str(), script->GetScriptCode().c_str()); switch (result) { case WREN_RESULT_COMPILE_ERROR: Logger::Trace(mLogCat, "Script compile error in module: %s", script->GetModuleName().c_str()); break; case WREN_RESULT_RUNTIME_ERROR: Logger::Trace(mLogCat, "Script runtime error in module: %s", script->GetModuleName().c_str()); break; case WREN_RESULT_SUCCESS: Logger::Trace(mLogCat, "Script %s run successfully", script->GetModuleName().c_str()); break; } } void WrenState::WriteFN(WrenVM* vm, const char* text) { std::string final = String::TrimEnd(text, "\n"); if (final.size() < 1) return; Logger::Info(mLogCat, final.c_str()); } void WrenState::ErrorFN(WrenVM* vm, WrenErrorType type, const char* module, int line, const char* message) { switch (type) { case WREN_ERROR_COMPILE: Logger::Error(mLogCat, "Script compile error: [%s line %d] %s\n", module, line, message); break; case WREN_ERROR_STACK_TRACE: Logger::Error(mLogCat, "[%s line %d] in %s\n", module, line, message); break; case WREN_ERROR_RUNTIME: Logger::Error(mLogCat, "Script Runtime Error: %s\n", message); break; } } }