Core state object for a hand-written Lua 5.1 interpreter used by the Roleplay framework. Owns the globals table and string metatable, loads/parses chunks into closures, runs calls with a call-depth limit and instruction budget, and implements metamethod dispatch for indexing, arithmetic, comparison, concatenation, length and tostring, plus error formatting with tracebacks and protected host calls via PCall.
using System;
using System.Collections.Generic;
using System.Text;
using RoleplayFramework.Lua.Compiler;
namespace RoleplayFramework.Lua;
/// <summary>
/// One isolated Lua environment (one per realm). Not thread-safe; use from the main thread.
/// Scripts can only reach what is placed in <see cref="Globals"/>: there is no io, os.execute,
/// debug, package, load/loadstring/dofile or reflection unless the host registers it.
/// </summary>
public sealed partial class LuaState
{
public const string RuntimeName = "RpLua";
public const string RuntimeVersion = "0.1.0";
public const string LanguageVersion = "Lua 5.1";
/// <summary>Maximum nested Lua/host calls before "stack overflow".</summary>
/// <remarks>
/// The interpreter recurses on the host (.NET) stack and s&box does not whitelist any stack-headroom
/// check, so this limit is what keeps a runaway recursion from killing the process. Measured cost is
/// ~1.7 KB (Release) to ~3 KB (Debug) of native stack per Lua call level; 100 levels stays well under 1 MB.
/// </remarks>
public int MaxCallDepth { get; set; } = 100;
/// <summary>
/// Max statements/loop iterations per top-level host call (0 = unlimited).
/// Exceeding it throws <see cref="LuaBudgetExceededException"/>, which pcall cannot catch.
/// </summary>
public long InstructionBudget { get; set; } = 5_000_000;
public LuaTable Globals { get; }
public LuaTable StringMetatable { get; }
/// <summary>Label used in diagnostics, e.g. "server", "client", "shared".</summary>
public string Name { get; }
/// <summary>Receives output of Lua's print().</summary>
public Action<string> PrintHandler { get; set; }
internal LuaFunction NextFunction { get; private set; }
readonly List<Frame> _frames = new();
int _callDepth;
long _steps;
public LuaState( string name = "lua" )
{
Name = name;
Globals = new LuaTable();
StringMetatable = new LuaTable();
OpenStandardLibraries();
}
// ------------------------------------------------------------ loading / running
/// <summary>Compiles source into a function. Throws <see cref="LuaSyntaxException"/>.</summary>
public LuaClosure Load( string source, string chunkName, LuaTable env = null )
{
var proto = Parser.ParseChunk( source, chunkName );
return new LuaClosure( proto, Array.Empty<Cell>(), env ?? Globals );
}
/// <summary>Compiles and runs source, returning its results.</summary>
public LuaValue[] DoString( string source, string chunkName, LuaTable env = null )
{
var fn = Load( source, chunkName, env );
return Call( LuaValue.FromFunction( fn ) );
}
/// <summary>
/// Calls a Lua value. When called from the host (not from inside Lua), the instruction
/// budget is reset for this call.
/// </summary>
public LuaValue[] Call( LuaValue fn, params LuaValue[] args )
{
args ??= LuaValue.EmptyArray;
if ( _frames.Count == 0 ) _steps = 0;
if ( fn.Type == LuaType.Function )
{
if ( fn.Obj is LuaClosure lc ) return CallClosure( lc, args );
return CallNative( (LuaNativeClosure)fn.Obj, args );
}
var mm = GetMetamethod( fn, "__call" );
if ( mm.IsNil ) throw new LuaRuntimeException( $"attempt to call a {fn.TypeName} value" );
var full = new LuaValue[args.Length + 1];
full[0] = fn;
args.CopyTo( full, 1 );
return Call( mm, full );
}
LuaValue[] CallClosure( LuaClosure c, LuaValue[] args )
{
var p = c.Proto;
if ( _callDepth >= MaxCallDepth ) throw new LuaRuntimeException( "stack overflow" );
var f = new Frame { Slots = new Cell[p.SlotCount], Closure = c, State = this, Line = p.Line };
for ( int i = 0; i < p.ParamCount; i++ )
f.Slots[i] = new Cell( i < args.Length ? args[i] : LuaValue.Nil );
if ( p.IsVararg )
{
if ( args.Length > p.ParamCount )
{
var va = new LuaValue[args.Length - p.ParamCount];
Array.Copy( args, p.ParamCount, va, 0, va.Length );
f.Varargs = va;
}
else f.Varargs = LuaValue.EmptyArray;
}
_callDepth++;
_frames.Add( f );
try
{
var r = p.Body.Exec( f );
return r == ExecResult.Return ? f.Returns : LuaValue.EmptyArray;
}
// An exception filter runs during the first (search) pass while this frame is still live,
// so the innermost Lua frame can stamp position + traceback without catching. Catching and
// rethrowing at every level would grow the native stack quadratically during unwinding.
catch ( LuaRuntimeException ex ) when ( AnnotateError( ex, f ) )
{
throw;
}
finally
{
_frames.RemoveAt( _frames.Count - 1 );
_callDepth--;
}
}
/// <summary>Always returns false (never catches); only decorates the error on its first sighting.</summary>
bool AnnotateError( LuaRuntimeException ex, Frame f )
{
if ( !ex.PositionApplied )
{
ex.PositionApplied = true;
if ( ex.Value.IsString ) ex.Value = LuaValue.FromString( $"{f.Closure.ChunkName}:{f.Line}: {ex.Value.AsString}" );
}
ex.LuaTraceback ??= BuildTraceback();
return false;
}
LuaValue[] CallNative( LuaNativeClosure fn, LuaValue[] args )
{
if ( _callDepth >= MaxCallDepth ) throw new LuaRuntimeException( "stack overflow" );
_callDepth++;
try
{
return fn.Body( this, args ) ?? LuaValue.EmptyArray;
}
catch ( Exception e ) when ( e is not LuaException )
{
// A host bug must not take down the realm; surface it as a Lua error instead.
throw new LuaRuntimeException( $"internal error in '{fn.Name}': {e.Message}" );
}
finally { _callDepth--; }
}
/// <summary>Instruction budget tick. Called per statement and per loop iteration.</summary>
internal void Step()
{
if ( ++_steps > InstructionBudget && InstructionBudget > 0 )
{
var where = _frames.Count > 0 ? $"{_frames[^1].Closure.ChunkName}:{_frames[^1].Line}: " : "";
throw new LuaBudgetExceededException( $"{where}script exceeded its instruction budget ({InstructionBudget:N0}); possible infinite loop" );
}
}
/// <summary>Adds host-side step cost (e.g. for pattern matching work).</summary>
internal void AddSteps( long n )
{
_steps += n - 1;
Step();
}
// ------------------------------------------------------------ error helpers
/// <summary>"chunk:line:" of the Lua function at <paramref name="level"/> (1 = innermost Lua function).</summary>
public string Where( int level )
{
int idx = _frames.Count - level;
if ( level < 1 || idx < 0 ) return "";
var f = _frames[idx];
return $"{f.Closure.ChunkName}:{f.Line}: ";
}
public string BuildTraceback()
{
var sb = new StringBuilder( "stack traceback:" );
int shown = 0;
for ( int i = _frames.Count - 1; i >= 0; i-- )
{
if ( shown++ >= 20 ) { sb.Append( "\n\t..." ); break; }
var f = _frames[i];
var p = f.Closure.Proto;
var what = p.Name == "main chunk" ? "main chunk" : $"function '{p.Name}'";
sb.Append( $"\n\t{p.ChunkName}:{f.Line}: in {what}" );
}
return sb.ToString();
}
// ------------------------------------------------------------ metatables
public LuaTable GetMetatable( LuaValue v ) => v.Type switch
{
LuaType.Table => ((LuaTable)v.Obj).Metatable,
LuaType.String => StringMetatable,
LuaType.UserData => ((LuaUserData)v.Obj).Metatable,
_ => null,
};
public LuaValue GetMetamethod( LuaValue v, string name )
{
var mt = GetMetatable( v );
return mt is null ? LuaValue.Nil : mt.Get( name );
}
// ------------------------------------------------------------ indexing
public LuaValue Index( LuaValue obj, LuaValue key )
{
for ( int loop = 0; loop < 100; loop++ )
{
LuaValue handler;
if ( obj.Type == LuaType.Table )
{
var t = (LuaTable)obj.Obj;
var v = t.Get( key );
if ( !v.IsNil ) return v;
if ( t.Metatable is null ) return LuaValue.Nil;
handler = t.Metatable.Get( "__index" );
if ( handler.IsNil ) return LuaValue.Nil;
}
else
{
handler = GetMetamethod( obj, "__index" );
if ( handler.IsNil ) throw new LuaRuntimeException( $"attempt to index a {obj.TypeName} value" );
}
if ( handler.Type == LuaType.Function )
{
var r = Call( handler, obj, key );
return r.Length > 0 ? r[0] : LuaValue.Nil;
}
obj = handler;
}
throw new LuaRuntimeException( "loop in gettable" );
}
public void SetIndex( LuaValue obj, LuaValue key, LuaValue value )
{
for ( int loop = 0; loop < 100; loop++ )
{
LuaValue handler;
if ( obj.Type == LuaType.Table )
{
var t = (LuaTable)obj.Obj;
if ( t.Metatable is null || !t.Get( key ).IsNil ) { t.Set( key, value ); return; }
handler = t.Metatable.Get( "__newindex" );
if ( handler.IsNil ) { t.Set( key, value ); return; }
}
else
{
handler = GetMetamethod( obj, "__newindex" );
if ( handler.IsNil ) throw new LuaRuntimeException( $"attempt to index a {obj.TypeName} value" );
}
if ( handler.Type == LuaType.Function )
{
Call( handler, obj, key, value );
return;
}
obj = handler;
}
throw new LuaRuntimeException( "loop in settable" );
}
// ------------------------------------------------------------ arithmetic & comparison
internal static double Mod( double a, double b ) => a - Math.Floor( a / b ) * b;
public static bool ToNumber( LuaValue v, out double d )
{
if ( v.Type == LuaType.Number ) { d = v.Number; return true; }
if ( v.Type == LuaType.String ) return LuaValue.TryParseNumber( v.AsString, out d );
d = 0;
return false;
}
static string EventName( BinOp op ) => op switch
{
BinOp.Add => "__add", BinOp.Sub => "__sub", BinOp.Mul => "__mul", BinOp.Div => "__div",
BinOp.Mod => "__mod", BinOp.Pow => "__pow", _ => "__concat",
};
internal LuaValue Arith( BinOp op, LuaValue a, LuaValue b )
{
if ( ToNumber( a, out var x ) && ToNumber( b, out var y ) )
{
return LuaValue.FromNumber( op switch
{
BinOp.Add => x + y,
BinOp.Sub => x - y,
BinOp.Mul => x * y,
BinOp.Div => x / y,
BinOp.Mod => Mod( x, y ),
_ => Math.Pow( x, y ),
} );
}
var ev = EventName( op );
var mm = GetMetamethod( a, ev );
if ( mm.IsNil ) mm = GetMetamethod( b, ev );
if ( mm.IsNil )
{
var bad = ToNumber( a, out _ ) ? b : a;
throw new LuaRuntimeException( $"attempt to perform arithmetic on a {bad.TypeName} value" );
}
var r = Call( mm, a, b );
return r.Length > 0 ? r[0] : LuaValue.Nil;
}
internal LuaValue Unm( LuaValue a )
{
if ( ToNumber( a, out var x ) ) return LuaValue.FromNumber( -x );
var mm = GetMetamethod( a, "__unm" );
if ( mm.IsNil ) throw new LuaRuntimeException( $"attempt to perform arithmetic on a {a.TypeName} value" );
var r = Call( mm, a, a );
return r.Length > 0 ? r[0] : LuaValue.Nil;
}
internal LuaValue Len( LuaValue a, string describe = null )
{
if ( a.Type == LuaType.String ) return LuaValue.FromNumber( a.AsString.Length );
var mm = GetMetamethod( a, "__len" );
if ( !mm.IsNil )
{
var r = Call( mm, a );
return r.Length > 0 ? r[0] : LuaValue.Nil;
}
if ( a.Type == LuaType.Table ) return LuaValue.FromNumber( ((LuaTable)a.Obj).Length );
throw new LuaRuntimeException( describe is null ? $"attempt to get length of a {a.TypeName} value" : $"attempt to get length of {describe} (a {a.TypeName} value)" );
}
internal LuaValue Concat( LuaValue a, LuaValue b )
{
if ( (a.Type == LuaType.String || a.Type == LuaType.Number) && (b.Type == LuaType.String || b.Type == LuaType.Number) )
return LuaValue.FromString( string.Concat( a.ToString(), b.ToString() ) );
var mm = GetMetamethod( a, "__concat" );
if ( mm.IsNil ) mm = GetMetamethod( b, "__concat" );
if ( mm.IsNil )
{
var bad = a.Type == LuaType.String || a.Type == LuaType.Number ? b : a;
throw new LuaRuntimeException( $"attempt to concatenate a {bad.TypeName} value" );
}
var r = Call( mm, a, b );
return r.Length > 0 ? r[0] : LuaValue.Nil;
}
public bool ValuesEqual( LuaValue a, LuaValue b )
{
if ( a.Type != b.Type ) return false;
if ( a.Equals( b ) ) return true;
if ( a.Type != LuaType.Table && a.Type != LuaType.UserData ) return false;
var mm1 = GetMetamethod( a, "__eq" );
var mm2 = GetMetamethod( b, "__eq" );
if ( mm1.IsNil || !mm1.Equals( mm2 ) ) return false;
var r = Call( mm1, a, b );
return r.Length > 0 && r[0].IsTruthy;
}
public bool LessThan( LuaValue a, LuaValue b )
{
if ( a.Type == LuaType.Number && b.Type == LuaType.Number ) return a.Number < b.Number;
if ( a.Type == LuaType.String && b.Type == LuaType.String ) return string.CompareOrdinal( a.AsString, b.AsString ) < 0;
return CompareMeta( a, b, "__lt" );
}
public bool LessEqual( LuaValue a, LuaValue b )
{
if ( a.Type == LuaType.Number && b.Type == LuaType.Number ) return a.Number <= b.Number;
if ( a.Type == LuaType.String && b.Type == LuaType.String ) return string.CompareOrdinal( a.AsString, b.AsString ) <= 0;
if ( a.Type == b.Type && !GetMetamethod( a, "__le" ).IsNil ) return CompareMeta( a, b, "__le" );
// Lua 5.1 fallback: a <= b == not (b < a)
return !CompareMeta( b, a, "__lt" );
}
bool CompareMeta( LuaValue a, LuaValue b, string ev )
{
if ( a.Type == b.Type )
{
var mm1 = GetMetamethod( a, ev );
var mm2 = GetMetamethod( b, ev );
if ( !mm1.IsNil && mm1.Equals( mm2 ) )
{
var r = Call( mm1, a, b );
return r.Length > 0 && r[0].IsTruthy;
}
}
if ( a.Type == b.Type )
throw new LuaRuntimeException( $"attempt to compare two {a.TypeName} values" );
throw new LuaRuntimeException( $"attempt to compare {a.TypeName} with {b.TypeName}" );
}
/// <summary>tostring() semantics including __tostring.</summary>
public string ToStringMeta( LuaValue v )
{
var mm = GetMetamethod( v, "__tostring" );
if ( !mm.IsNil )
{
var r = Call( mm, v );
var s = r.Length > 0 ? r[0] : LuaValue.Nil;
if ( s.Type != LuaType.String && s.Type != LuaType.Number )
throw new LuaRuntimeException( "'__tostring' must return a string" );
return s.ToString();
}
return v.ToString();
}
// ------------------------------------------------------------ host registration helpers
public LuaNativeClosure Register( string name, LuaNativeFunction fn ) => Register( Globals, name, fn );
public static LuaNativeClosure Register( LuaTable table, string name, LuaNativeFunction fn )
{
var c = new LuaNativeClosure( name, fn );
table.Set( name, LuaValue.FromFunction( c ) );
return c;
}
/// <summary>Gets or creates a library table in globals, e.g. "hook".</summary>
public LuaTable GetOrCreateLibrary( string name )
{
var v = Globals.Get( name );
if ( v.IsTable ) return v.AsTable;
var t = new LuaTable();
Globals.Set( name, t );
return t;
}
/// <summary>
/// Protected host call: runs <paramref name="fn"/> and converts script failures into a result
/// instead of an exception. Use this at every engine→Lua boundary so one bad script can't crash the host.
/// </summary>
public LuaCallResult PCall( LuaValue fn, params LuaValue[] args )
{
try
{
return new LuaCallResult( true, Call( fn, args ), null, null );
}
catch ( LuaRuntimeException e )
{
return new LuaCallResult( false, LuaValue.EmptyArray, e.Message, e.LuaTraceback );
}
catch ( LuaException e )
{
return new LuaCallResult( false, LuaValue.EmptyArray, e.Message, BuildTraceback() );
}
}
internal static LuaValue[] One( LuaValue v ) => new[] { v };
}
public readonly record struct LuaCallResult( bool Success, LuaValue[] Results, string Error, string Traceback );