From 08038000ccb433f55528a1a95f63166bd6146e58 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:48 +0000 Subject: [PATCH] feat(Script): bounded Lua evaluator with transactional host results (#17) --- include/Void/Script/Lua.hpp | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 include/Void/Script/Lua.hpp diff --git a/include/Void/Script/Lua.hpp b/include/Void/Script/Lua.hpp new file mode 100644 index 0000000..33aa185 --- /dev/null +++ b/include/Void/Script/Lua.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Void::Script +{ + +/// Host function: receives integer arguments, returns an integer or an error +/// message. It must not commit externally visible state itself; the evaluator +/// records each call in `Result::host_calls` so the caller can commit after a +/// successful evaluation. +using HostFunction = std::function( + std::span)>; + +struct Host { + std::string name; + HostFunction function; +}; + +/// Bounded Lua text evaluator. +/// +/// Each `evaluate` call creates a fresh, isolated Lua state, applies the +/// allocator, instruction and host-call limits, exposes the integer-keyed +/// inputs as `input[key]`, registers the host functions as globals, and runs +/// the chunk with a protected call. Only integer return values are accepted +/// and collected into an owned result. On failure the state is discarded, so +/// inputs and the caller's host state are untouched; a later valid evaluation +/// starts clean. +class LuaEvaluator +{ + public: + + explicit LuaEvaluator(Limits limits = Limits{}, + std::vector hosts = {}) + : limits_(limits) + , hosts_(std::move(hosts)) + { + } + + [[nodiscard]] const Limits& limits() const noexcept { return limits_; } + + [[nodiscard]] std::expected + evaluate(std::string_view source, + std::span inputs = {}) const; + + private: + + Limits limits_; + std::vector hosts_; +}; + +} // namespace Void::Script