The value type for a hand written Lua 5.1 interpreter. A tagged struct holding nil, boolean, number, string, table, function or userdata, with constructors, implicit conversions, truthiness tests, equality and hashing, Lua style number formatting and string to number parsing. Also defines LuaUserData, the opaque wrapper for host objects exposed to scripts.
using System;
using System.Globalization;
namespace RoleplayFramework.Lua;
public enum LuaType : byte
{
Nil,
Boolean,
Number,
String,
Table,
Function,
UserData,
}
/// <summary>
/// A single Lua value. Numbers are doubles (Lua 5.1 semantics). Booleans store 1/0 in <see cref="Number"/>.
/// </summary>
public readonly struct LuaValue : IEquatable<LuaValue>
{
public readonly LuaType Type;
public readonly double Number;
public readonly object Obj;
LuaValue( LuaType type, double number, object obj )
{
Type = type;
Number = number;
Obj = obj;
}
public static readonly LuaValue Nil = default;
public static readonly LuaValue True = new( LuaType.Boolean, 1, null );
public static readonly LuaValue False = new( LuaType.Boolean, 0, null );
public static readonly LuaValue[] EmptyArray = Array.Empty<LuaValue>();
public static LuaValue FromNumber( double d ) => new( LuaType.Number, d, null );
public static LuaValue FromBool( bool b ) => b ? True : False;
public static LuaValue FromString( string s ) => s is null ? Nil : new LuaValue( LuaType.String, 0, s );
public static LuaValue FromTable( LuaTable t ) => t is null ? Nil : new LuaValue( LuaType.Table, 0, t );
public static LuaValue FromFunction( LuaFunction f ) => f is null ? Nil : new LuaValue( LuaType.Function, 0, f );
public static LuaValue FromUserData( LuaUserData u ) => u is null ? Nil : new LuaValue( LuaType.UserData, 0, u );
public static implicit operator LuaValue( double d ) => FromNumber( d );
public static implicit operator LuaValue( int i ) => FromNumber( i );
public static implicit operator LuaValue( bool b ) => FromBool( b );
public static implicit operator LuaValue( string s ) => FromString( s );
public static implicit operator LuaValue( LuaTable t ) => FromTable( t );
public static implicit operator LuaValue( LuaFunction f ) => FromFunction( f );
public bool IsNil => Type == LuaType.Nil;
public bool IsNumber => Type == LuaType.Number;
public bool IsString => Type == LuaType.String;
public bool IsTable => Type == LuaType.Table;
public bool IsFunction => Type == LuaType.Function;
/// <summary>Lua truthiness: everything except nil and false is true.</summary>
public bool IsTruthy => Type != LuaType.Nil && !(Type == LuaType.Boolean && Number == 0);
public bool AsBool => IsTruthy;
public string AsString => Obj as string;
public LuaTable AsTable => Obj as LuaTable;
public LuaFunction AsFunction => Obj as LuaFunction;
public LuaUserData AsUserData => Obj as LuaUserData;
public string TypeName => TypeNameOf( Type );
public static string TypeNameOf( LuaType t ) => t switch
{
LuaType.Nil => "nil",
LuaType.Boolean => "boolean",
LuaType.Number => "number",
LuaType.String => "string",
LuaType.Table => "table",
LuaType.Function => "function",
_ => "userdata",
};
public bool Equals( LuaValue other )
{
if ( Type != other.Type ) return false;
return Type switch
{
LuaType.Nil => true,
LuaType.Boolean or LuaType.Number => Number == other.Number,
LuaType.String => string.Equals( (string)Obj, (string)other.Obj, StringComparison.Ordinal ),
_ => ReferenceEquals( Obj, other.Obj ),
};
}
public override bool Equals( object obj ) => obj is LuaValue v && Equals( v );
public override int GetHashCode()
{
switch ( Type )
{
case LuaType.Nil: return 0;
case LuaType.Boolean: return Number == 0 ? 1 : 2;
case LuaType.Number: return Number == 0 ? 0 : Number.GetHashCode();
case LuaType.String: return StringComparer.Ordinal.GetHashCode( (string)Obj );
default: return Obj.GetHashCode();
}
}
public static bool operator ==( LuaValue a, LuaValue b ) => a.Equals( b );
public static bool operator !=( LuaValue a, LuaValue b ) => !a.Equals( b );
/// <summary>Raw string conversion (no __tostring). Use <see cref="LuaState.ToStringMeta"/> for print/tostring.</summary>
public override string ToString()
{
return Type switch
{
LuaType.Nil => "nil",
LuaType.Boolean => Number != 0 ? "true" : "false",
LuaType.Number => NumberToString( Number ),
LuaType.String => (string)Obj,
LuaType.Table => $"table: 0x{IdOf( Obj ):x8}",
LuaType.Function => $"function: 0x{IdOf( Obj ):x8}",
_ => $"userdata: 0x{IdOf( Obj ):x8}",
};
}
// LuaTable, LuaFunction and LuaUserData never override GetHashCode, so this is identity-based.
static int IdOf( object o ) => o.GetHashCode();
/// <summary>Formats a number like Lua's "%.14g".</summary>
public static string NumberToString( double d )
{
if ( double.IsNaN( d ) ) return "nan";
if ( double.IsPositiveInfinity( d ) ) return "inf";
if ( double.IsNegativeInfinity( d ) ) return "-inf";
if ( d == Math.Floor( d ) && Math.Abs( d ) < 1e15 )
{
if ( d == 0 ) return 1 / d < 0 ? "-0" : "0";
return ((long)d).ToString( CultureInfo.InvariantCulture );
}
return d.ToString( "G14", CultureInfo.InvariantCulture ).ToLowerInvariant();
}
/// <summary>Lua string-to-number coercion (decimal, hex, exponent, surrounding whitespace).</summary>
public static bool TryParseNumber( string s, out double result )
{
result = 0;
if ( s is null ) return false;
s = s.Trim();
if ( s.Length == 0 ) return false;
bool neg = false;
var body = s;
if ( body[0] == '-' || body[0] == '+' )
{
neg = body[0] == '-';
body = body.Substring( 1 );
}
if ( body.Length > 2 && body[0] == '0' && (body[1] == 'x' || body[1] == 'X') )
{
double v = 0;
for ( int i = 2; i < body.Length; i++ )
{
int digit = HexDigit( body[i] );
if ( digit < 0 ) return false;
v = v * 16 + digit;
}
result = neg ? -v : v;
return true;
}
// Reject things double.Parse accepts but Lua doesn't (e.g. "Infinity", "NaN", thousands separators).
foreach ( var c in body )
{
if ( !(char.IsAsciiDigit( c ) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-') )
return false;
}
if ( !double.TryParse( body, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var parsed ) )
return false;
result = neg ? -parsed : parsed;
return true;
}
public static int HexDigit( char c )
{
if ( c >= '0' && c <= '9' ) return c - '0';
if ( c >= 'a' && c <= 'f' ) return c - 'a' + 10;
if ( c >= 'A' && c <= 'F' ) return c - 'A' + 10;
return -1;
}
}
/// <summary>
/// Opaque host object exposed to Lua. Lua can only reach what its metatable exposes;
/// the wrapped C# object is never reachable by scripts.
/// </summary>
public class LuaUserData
{
public object Value { get; }
public LuaTable Metatable { get; set; }
public LuaUserData( object value, LuaTable metatable = null )
{
Value = value;
Metatable = metatable;
}
}