Files
live-wallpaper/src/script.cpp

84 lines
2.5 KiB
C++

#include "script.h"
#include <SDL3/SDL_log.h>
Script::Script(sol::state& lua, const std::string& filepath) : m_lua(lua) {
auto result = m_lua.safe_script_file(filepath, sol::script_pass_on_error);
if (!result.valid()) {
sol::error err = result;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to load script '%s': %s",
filepath.c_str(), err.what());
return;
}
// Bind lifecycle functions
sol::object createObj = m_lua["_create"];
if (createObj.is<sol::protected_function>()) {
m_create = createObj.as<sol::protected_function>();
m_hasCreate = true;
}
sol::object updateObj = m_lua["_update"];
if (updateObj.is<sol::protected_function>()) {
m_update = updateObj.as<sol::protected_function>();
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Script '%s' missing required '_update(dt)' function",
filepath.c_str());
}
sol::object renderObj = m_lua["_render"];
if (renderObj.is<sol::protected_function>()) {
m_render = renderObj.as<sol::protected_function>();
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Script '%s' missing required '_render' function",
filepath.c_str());
}
sol::object destroyObj = m_lua["_destroy"];
if (destroyObj.is<sol::protected_function>()) {
m_destroy = destroyObj.as<sol::protected_function>();
m_hasDestroy = true;
}
}
Script::~Script() {
Destroy();
}
void Script::Create() {
if (!m_hasCreate) return;
auto result = m_create();
if (!result.valid()) {
sol::error err = result;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "_create error: %s", err.what());
}
}
void Script::Update(float dt) {
if (!m_update.valid()) return;
auto result = m_update(dt);
if (!result.valid()) {
sol::error err = result;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "_update error: %s", err.what());
}
}
void Script::Render() {
if (!m_render.valid()) return;
auto result = m_render();
if (!result.valid()) {
sol::error err = result;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "_render error: %s", err.what());
}
}
void Script::Destroy() {
if (!m_hasDestroy) return;
auto result = m_destroy();
if (!result.valid()) {
sol::error err = result;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "_destroy error: %s", err.what());
}
m_hasDestroy = false; // Prevent double-destroy
}