using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
///
/// One script's Lua state (MoonSharp, Lua 5.2), run on the plugin pump thread.
///
/// Every piece of script code runs as a coroutine ("thread") resumed from
/// : the main chunk, each event handler call and each
/// spawn. sleep(ms) parks the thread until its wake time, await(action)
/// until the action's IsFinished is true, and MoonSharp's auto-yield pauses any
/// thread that runs too long without sleeping, so an endless loop slows the script down
/// instead of freezing the client. A script stays running while it has live threads,
/// handlers (v1 on, v2 events, commands) or a global OnBotTick; Stop clears them.
///
internal sealed class LuaScriptHost
{
/// C:\Games\RynthSuite\RynthLua\Scripts (see ).
public static string ScriptFolder => RynthLuaPaths.Scripts;
/// Where scripts lived while Lua was part of RynthAi (copied over once, then left alone).
public static string LegacyScriptFolder => RynthLuaPaths.LegacyScripts;
private const int MaxConsoleLines = 400;
// VM instructions before a forced pause. A forced pause resumes at once while the tick has time,
// so this only sets how often the time budget and the memory guard look: 1,000 (it was 5,000,
// which let one stretch of string.rep in a loop use over a gigabyte before the guard saw it).
private const int AutoYieldCounter = 1_000;
private sealed class LuaThread
{
public DynValue Co = DynValue.Nil; // set when the thread first runs (TakeCoroutine)
public DynValue Fn = DynValue.Nil; // the function, until then
public long WakeAt;
public Func? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty();
public bool Started;
/// Runs on a pooled worker coroutine (see ): it ends by yielding the done token.
public bool Pooled;
/// Called once when the thread ends: its return values, or the error message.
public Action? OnDone;
}
// ── Worker coroutines ───────────────────────────────────────────────────
//
// MoonSharp 2.0 gives every coroutine two 131,072-slot stacks the moment it is created:
// about 1 MB in the 32-bit client (2 MB in a 64-bit process), all on the Large Object Heap,
// which only a full collection frees. RynthLua used to make one per event handler call and
// per hud pass, so a 194-line /myquests read cost each script with a chat handler ~200 MB and
// a 20-per-second window 20 MB/s. The heap figure the memory guard reads then passed 800 MB
// and the guard stopped scripts that had done nothing wrong (2026-11-30).
// Now a thread runs on a worker: a Lua loop that calls the function it is given, yields the
// done token with the results, and waits for the next function. A worker whose function
// ended normally goes back to a small pool; one that raised an error, or was aborted or
// stopped part-way, is simply dropped (it can't be reused).
private const string WorkerCode = @"
local DONE, yield, select, unpack = ...
local function packn(...) return { n = select('#', ...), ... } end
return function(fn, args)
while true do
fn, args = yield(DONE, packn(fn(unpack(args, 1, args.n))))
end
end";
/// Idle workers kept per script; more than this are left to the GC.
internal const int MaxIdleWorkers = 8;
private DynValue _workerFn = DynValue.Nil;
private Table? _doneToken;
private readonly Stack _idleWorkers = new();
/// Test hook: workers made since the script started (a fresh coroutine each).
internal int WorkersCreated { get; private set; }
///
/// Makes the worker function from the state's own coroutine.yield, select and table.unpack,
/// taken before any script code runs (a script that replaces them later doesn't touch workers).
///
private void CreateWorkers(Script s)
{
_idleWorkers.Clear();
_workerFn = DynValue.Nil;
_doneToken = null;
WorkersCreated = 0;
try
{
DynValue co = s.Globals.Get("coroutine");
DynValue tbl = s.Globals.Get("table");
DynValue yield = co.Type == DataType.Table ? co.Table.Get("yield") : DynValue.Nil;
DynValue select = s.Globals.Get("select");
DynValue unpack = tbl.Type == DataType.Table ? tbl.Table.Get("unpack") : DynValue.Nil;
if (unpack.IsNil()) unpack = s.Globals.Get("unpack");
if (yield.IsNil() || select.IsNil() || unpack.IsNil()) return; // old behaviour: a coroutine per thread
var token = new Table(s);
DynValue factory = s.LoadString(WorkerCode, new Table(s), "rynth worker");
DynValue fn = s.Call(factory, DynValue.NewTable(token), yield, select, unpack);
if (fn.Type != DataType.Function) return;
_doneToken = token;
_workerFn = fn;
}
catch { _workerFn = DynValue.Nil; _doneToken = null; }
}
/// An idle worker, or a new one; null when workers aren't available (a coroutine per thread then).
internal DynValue? RentWorker()
{
if (_script == null || _workerFn.Type != DataType.Function) return null;
while (_idleWorkers.Count > 0)
{
DynValue w = _idleWorkers.Pop();
if (w.Coroutine.State is CoroutineState.Suspended or CoroutineState.NotStarted) return w;
}
WorkersCreated++;
return _script.CreateCoroutine(_workerFn);
}
/// Puts a worker that yielded the done token back in the pool.
internal void ReturnWorker(DynValue worker)
{
if (_script == null || worker.Coroutine.State is not (CoroutineState.Suspended or CoroutineState.NotStarted)) return;
if (_idleWorkers.Count < MaxIdleWorkers) _idleWorkers.Push(worker);
}
/// What a worker is resumed with to run (...).
internal DynValue[] WorkerArgs(DynValue fn, DynValue[] args)
{
var t = new Table(_script);
for (int i = 0; i < args.Length; i++) t.Set(i + 1, args[i]);
t.Set("n", DynValue.NewNumber(args.Length));
return new[] { fn, DynValue.NewTable(t) };
}
/// True when (a worker's Resume result) says its function returned.
internal bool IsWorkerDone(DynValue r) =>
_doneToken != null && r.Type == DataType.Tuple && r.Tuple is { Length: 2 } tu
&& tu[0].Type == DataType.Table && ReferenceEquals(tu[0].Table, _doneToken);
/// The function's return values from a done worker's result: Void for none, the value for one, else a tuple.
internal static DynValue WorkerResults(DynValue r)
{
DynValue packed = r.Tuple[1];
if (packed.Type != DataType.Table) return DynValue.Void;
Table t = packed.Table;
DynValue nv = t.RawGet("n") ?? DynValue.Nil;
int n = nv.Type == DataType.Number ? (int)nv.Number : 0;
if (n <= 0) return DynValue.Void;
if (n == 1) return t.Get(1);
var values = new DynValue[n];
for (int i = 0; i < n; i++) values[i] = t.Get(i + 1);
return DynValue.NewTuple(values);
}
private readonly Action _log;
private readonly Action