Decompiled source of ShipSort v5.1.3

baer1.ShipSort.dll

Decompiled 4 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ChatCommandAPI;
using ChatCommandAPI.Utils;
using GameNetcodeStuff;
using HarmonyLib;
using LethalModUtils;
using LethalShipSort.Commands;
using LethalShipSort.LuaObjects;
using Lua;
using Lua.Standard;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("DunGen")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.ASPP")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.UnityNav")]
[assembly: IgnoresAccessChecksTo("EasyTextEffects")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.CoreUtils")]
[assembly: IgnoresAccessChecksTo("Unity.XR.Management")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.ConformanceAutomation")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MetaQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MockRuntime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.OculusQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.RuntimeDebugger")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpatialTracking")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("UnityEngine.XR.LegacyInputHelpers")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("baer1.ShipSort")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("5.1.3.0")]
[assembly: AssemblyInformationalVersion("5.1.3+8992e05082dec3ea40fb400deb29bba6e20e8bb5")]
[assembly: AssemblyProduct("LethalShipSort")]
[assembly: AssemblyTitle("baer1.ShipSort")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.1.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalShipSort
{
	[BepInPlugin("baer1.ShipSort", "LethalShipSort", "5.1.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class LethalShipSort : BaseUnityPlugin
	{
		internal const string NETWORK_MESSAGE_NAME = "baer1.ShipSort";

		internal const string PREFIX = "[ShipSort] ";

		internal const int MAX_SHARE = 104857600;

		internal const int LAYER_MASK = 268437761;

		private const float VERTICAL_OFFSET = 0.02f;

		internal static Harmony Harmony = null;

		private static readonly Version VERSION = new Version("5.1.3");

		private ConfigEntry<string> scriptPath;

		private ConfigEntry<uint> timeout;

		private ConfigEntry<bool> autoSort;

		private ConfigEntry<bool> shareConfig;

		private ConfigEntry<bool> useSharedConfig;

		private ConfigEntry<int> sharedConfigSizeLimit;

		private string? cachedScript;

		private MemoryStream? cachedCompressedScript;

		private string? cachedSharedScript;

		public static LethalShipSort Instance { get; private set; } = null;

		internal static ManualLogSource Logger { get; private set; } = null;

		public string ScriptPath
		{
			get
			{
				if (!Path.IsPathRooted(scriptPath.Value))
				{
					return Path.Join(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath).AsSpan(), scriptPath.Value.AsSpan());
				}
				return scriptPath.Value;
			}
		}

		public int Timeout => (int)Math.Min(2147483647u, timeout.Value);

		public bool AutoSort => autoSort.Value;

		public bool ShareConfig => shareConfig.Value;

		public bool UseSharedConfig
		{
			get
			{
				if (useSharedConfig.Value)
				{
					return cachedSharedScript != null;
				}
				return false;
			}
		}

		public int SharedConfigSizeLimit => sharedConfigSizeLimit.Value;

		private void Awake()
		{
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			try
			{
				_verifyDeps();
			}
			catch (FileNotFoundException)
			{
				Logger.LogFatal((object)"Missing required assembly, please verify your mod files");
				throw;
			}
			catch (TypeLoadException)
			{
				Logger.LogFatal((object)"Incompatible required assembly, please verify your mod files");
				throw;
			}
			scriptPath = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ScriptPath", "sort.lua", "The item sorting script to use (absolute path or relative to this config file)");
			timeout = ((BaseUnityPlugin)this).Config.Bind<uint>("General", "Timeout", 5u, "The maximum execution time for the sorting script in seconds (prevents freezing, 0 to disable [NOT RECOMMENDED])");
			autoSort = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoSort", false, "[HOST-ONLY] Automatically sorts all items before the ship lands and after it takes off");
			shareConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Networking", "ShareConfig", true, "Shares your sorting script to other players with the mod when they join your lobby");
			useSharedConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Networking", "UseSharedConfig", true, "Whether to use sorting scripts sent by the lobby host");
			sharedConfigSizeLimit = ((BaseUnityPlugin)this).Config.Bind<int>("Networking", "SharedConfigSizeLimit", 10485760, "Maximum size for shared configs that can be received (in bytes, default: 10MB)");
			scriptPath.SettingChanged += ConfigChanged;
			shareConfig.SettingChanged += ConfigChanged;
			Harmony = new Harmony("baer1.ShipSort");
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching!");
			new SortCommand();
			new SortReloadCommand();
			new SortStatusCommand();
			Logger.LogInfo((object)"baer1.ShipSort v5.1.3 has loaded!");
			static void _verifyDeps()
			{
				Logger.LogDebug((object)("LuaCSharp loaded: " + Assembly.GetAssembly(typeof(LuaState)).Location));
				Logger.LogDebug((object)("LuaCSharp Annotations loaded: " + Assembly.GetAssembly(typeof(LuaObjectAttribute)).Location));
				Logger.LogDebug((object)("Microsoft.Bcl.TimeProvider loaded: " + Assembly.GetAssembly(typeof(TimeProvider)).Location));
				Logger.LogDebug((object)("System.Runtime.CompilerServices.Unsafe loaded: " + Assembly.GetAssembly(typeof(Unsafe)).Location));
			}
		}

		internal FastBufferWriter CreateNetworkMessage()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			Logger.LogDebug((object)(">> CreateNetworkMessage cachedCompressedScript:" + ((cachedCompressedScript == null) ? "null" : $"[{cachedCompressedScript.Length}]") + " cachedScript:" + ((cachedScript == null) ? "null" : $"[{cachedScript.Length}]")));
			if (cachedCompressedScript == null)
			{
				return new FastBufferWriter(0, (Allocator)2, -1);
			}
			if (cachedScript == null)
			{
				throw new InvalidOperationException("cachedScript is null, but cachedCompressedScript is not");
			}
			if (cachedCompressedScript.Length > 2147483642)
			{
				throw new InsufficientMemoryException("cachedCompressedScript data too large");
			}
			MemoryStream memoryStream = cachedCompressedScript;
			FastBufferWriter result = default(FastBufferWriter);
			((FastBufferWriter)(ref result))..ctor((int)cachedCompressedScript.Length + 5, (Allocator)2, -1);
			int length = cachedScript.Length;
			((FastBufferWriter)(ref result)).WriteValue<int>(ref length, default(ForPrimitives));
			((FastBufferWriter)(ref result)).WriteBytes(memoryStream.GetBuffer(), (int)cachedCompressedScript.Length, 0);
			return result;
		}

		internal void ConfigChanged(object sender, EventArgs eventArgs)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Logger.LogDebug((object)">> ConfigChanged");
				NetworkManager singleton = NetworkManager.Singleton;
				if (singleton.IsServer)
				{
					try
					{
						ReloadScript();
					}
					catch
					{
					}
					singleton.CustomMessagingManager.SendNamedMessageToAll("baer1.ShipSort", CreateNetworkMessage(), (NetworkDelivery)4);
				}
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Error sharing script: {arg}");
			}
		}

		internal void ClearSharedScript()
		{
			Logger.LogDebug((object)(">> ClearSharedScript cachedSharedScript:" + ((cachedSharedScript == null) ? "null" : $"[{cachedSharedScript.Length}]")));
			cachedSharedScript = null;
		}

		internal void ReloadScript()
		{
			try
			{
				Logger.LogDebug((object)">> ReloadScript");
				using FileStream fileStream = File.Open(ScriptPath, FileMode.Open, FileAccess.Read);
				if (fileStream.Length > int.MaxValue)
				{
					throw new InsufficientMemoryException("file data too large");
				}
				byte[] array = new byte[(int)fileStream.Length];
				int num = fileStream.Read(array, 0, (int)fileStream.Length);
				if (num < fileStream.Length)
				{
					throw new EndOfStreamException();
				}
				cachedScript = Encoding.UTF8.GetString(array);
				if (ShareConfig && NetworkManager.Singleton.IsServer)
				{
					cachedCompressedScript = new MemoryStream();
					using (GZipStream destination = new GZipStream(cachedCompressedScript, CompressionLevel.Optimal, leaveOpen: true))
					{
						fileStream.Seek(0L, SeekOrigin.Begin);
						fileStream.CopyTo(destination);
					}
					if (cachedCompressedScript.Length <= 0)
					{
						Logger.LogWarning((object)$"Compressed script size is invalid: {cachedCompressedScript.Length} bytes");
						cachedCompressedScript.Dispose();
						cachedCompressedScript = null;
					}
					else if (cachedCompressedScript.Length > 104857600)
					{
						Chat.PrintWarning("[ShipSort] Your config script is too large to share: expected less than " + Utils.BytesToString(104857600) + ", got " + Utils.BytesToString((int)cachedCompressedScript.Length));
						cachedCompressedScript.Dispose();
						cachedCompressedScript = null;
					}
					else
					{
						Logger.LogInfo((object)$"Compressed local script to {cachedCompressedScript.Length} bytes");
					}
				}
				else
				{
					Logger.LogDebug((object)"Config sharing disabled");
					cachedCompressedScript?.Dispose();
					cachedCompressedScript = null;
				}
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Error reloading script: {arg}");
				cachedScript = null;
				cachedCompressedScript?.Dispose();
				cachedCompressedScript = null;
				throw;
			}
		}

		internal static void NetworkMessageHandler(ulong senderClientId, FastBufferReader messagePayload)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			int num = ((FastBufferReader)(ref messagePayload)).Length - 8;
			Logger.LogDebug((object)string.Format(">> {0}({1}: {2}, {3}: [{4}]) {5}:{6}", "NetworkMessageHandler", "senderClientId", senderClientId, "messagePayload", ((FastBufferReader)(ref messagePayload)).Length, "payloadLength", num));
			if (senderClientId != 0L)
			{
				Logger.LogError((object)$"Expected network message from host (0), received from {senderClientId}");
			}
			else
			{
				if (NetworkManager.Singleton.IsServer)
				{
					return;
				}
				LethalShipSort instance = Instance;
				if (num <= 0)
				{
					instance.ClearSharedScript();
					return;
				}
				if (num <= 4)
				{
					instance.ClearSharedScript();
					Logger.LogWarning((object)$"Not enough data to read shared config: {num} bytes");
					return;
				}
				int num2 = default(int);
				((FastBufferReader)(ref messagePayload)).ReadValue<int>(ref num2, default(ForPrimitives));
				if (num2 <= 0)
				{
					instance.ClearSharedScript();
					Logger.LogWarning((object)$"Shared config size invalid: {num2} bytes");
					return;
				}
				if (instance.SharedConfigSizeLimit <= 0)
				{
					Logger.LogDebug((object)"Shared config receiving disabled");
					return;
				}
				if (num2 <= instance.SharedConfigSizeLimit)
				{
					byte[] array = new byte[num - 4];
					((FastBufferReader)(ref messagePayload)).ReadBytes(ref array, array.Length, 0);
					Logger.LogDebug((object)$"Read {array.Length} bytes (decodes to {num2} bytes)");
					using MemoryStream stream = new MemoryStream(array);
					using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress);
					byte[] array2 = new byte[num2];
					int num3 = gZipStream.Read(array2, 0, num2);
					if (num3 != num2)
					{
						instance.ClearSharedScript();
						Logger.LogWarning((object)$"Shared config size does not match decompressed data size: expected {num2} bytes, got {num3} bytes");
					}
					else if (gZipStream.ReadByte() != -1)
					{
						instance.ClearSharedScript();
						Logger.LogWarning((object)$"Shared config size does not match decompressed data size: expected {num2} bytes, got more");
					}
					else
					{
						instance.cachedSharedScript = Encoding.UTF8.GetString(array2);
						Logger.LogDebug((object)$"<< Loaded script ({num2} bytes)");
					}
					return;
				}
				instance.ClearSharedScript();
				Chat.PrintWarning("[ShipSort] Shared config exceeded size limit: " + Utils.BytesToString(num2));
			}
		}

		public static IEnumerable<GrabbableObject> FilterItems(IEnumerable<GrabbableObject> items, PlayerControllerB localPlayer)
		{
			return items.Where((GrabbableObject i) => FilterItem(i, localPlayer));
		}

		public static bool FilterItem(GrabbableObject item, PlayerControllerB localPlayer)
		{
			if (!((Object)(object)item.playerHeldBy != (Object)null) || !((Object)(object)item.playerHeldBy == (Object)(object)localPlayer))
			{
				if (item != null && !item.isHeld)
				{
					return !item.isPocketed;
				}
				return false;
			}
			return true;
		}

		internal static void TryAutoSort(StartOfRound sor)
		{
			//IL_0021: Expected O, but got Unknown
			LethalShipSort instance = Instance;
			if (!instance.AutoSort)
			{
				return;
			}
			try
			{
				instance.Sort(sor, Array.Empty<string>(), isAutoSort: true);
			}
			catch (CommandException ex)
			{
				CommandException ex2 = ex;
				Chat.PrintWarning("Autosort failed: " + ((Exception)(object)ex2).Message);
			}
			catch (Exception ex3)
			{
				Chat.PrintWarning("Autosort failed, check the logs for more details");
				Logger.LogError((object)ex3);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool Sort(StartOfRound sor, IEnumerable<string> args, bool isAutoSort = false)
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			if (isAutoSort && !((NetworkBehaviour)sor).IsServer)
			{
				return true;
			}
			if (!sor.inShipPhase && !isAutoSort)
			{
				throw new ShipIsLandedException();
			}
			LethalShipSort instance = Instance;
			GrabbableObject[] array = (from i in Object.FindObjectsByType<GrabbableObject>((FindObjectsInactive)0, (FindObjectsSortMode)1)
				where ((NetworkBehaviour)i).IsSpawned
				select i).ToArray();
			int num = array.Length;
			array = FilterItems(array, sor.localPlayerController).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			try
			{
				bool flag = UseSharedConfig;
				if (cachedScript == null && !flag)
				{
					throw new CommandException("Script '" + ScriptPath + "' could not be found");
				}
				Sort(array, sor.localPlayerController, RoundManager.Instance.currentLevel, TimeOfDay.Instance.daysUntilDeadline, (Object)(object)Object.FindAnyObjectByType<VehicleController>((FindObjectsInactive)0) != (Object)null, Object.FindFirstObjectByType<ShipLights>().areLightsOn, sor.unlockablesList, flag ? cachedSharedScript : cachedScript, flag ? "shared.lua" : ScriptPath, args, (uint)(num - array.Length), isAutoSort);
				return true;
			}
			catch (ArgumentException ex)
			{
				throw new CommandException("Script result invalid: " + ex.Message);
			}
			catch (TimeoutException)
			{
				throw new CommandException("Script execution timed out");
			}
			catch (LuaCompileException ex3)
			{
				LuaCompileException ex4 = ex3;
				Logger.LogError((object)ex4);
				throw new CommandException("Script compilation error: " + ((Exception)(object)ex4).Message.Trim() + "\nCheck the logs for more details");
			}
			catch (LuaRuntimeException ex5)
			{
				LuaRuntimeException ex6 = ex5;
				Logger.LogDebug((object)ex6);
				Logger.LogError((object)ex6.LuaTraceback);
				throw new CommandException("Script error: " + ((Exception)(object)ex6).Message.Trim() + "\nCheck the logs for more details");
			}
		}

		public static void Sort(GrabbableObject[] items, PlayerControllerB player, SelectableLevel currentLevel, int daysUntilDeadline, bool cruiser, bool lights, UnlockablesList unlockablesList, string scriptContent, string scriptPath, IEnumerable<string> args, uint skipped = 0u, bool isAutoSort = false)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Expected O, but got Unknown
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Expected O, but got Unknown
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Expected O, but got Unknown
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Expected O, but got Unknown
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0404: Unknown result type (might be due to invalid IL or missing references)
			//IL_040e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0428: Unknown result type (might be due to invalid IL or missing references)
			//IL_042d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0437: Unknown result type (might be due to invalid IL or missing references)
			//IL_0451: Unknown result type (might be due to invalid IL or missing references)
			//IL_0456: Unknown result type (might be due to invalid IL or missing references)
			//IL_0460: Unknown result type (might be due to invalid IL or missing references)
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0489: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04db: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_051e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0523: Unknown result type (might be due to invalid IL or missing references)
			//IL_052d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0547: Unknown result type (might be due to invalid IL or missing references)
			//IL_0552: Unknown result type (might be due to invalid IL or missing references)
			//IL_056c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0577: Unknown result type (might be due to invalid IL or missing references)
			//IL_0591: Unknown result type (might be due to invalid IL or missing references)
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_086d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0872: Unknown result type (might be due to invalid IL or missing references)
			//IL_0858: Unknown result type (might be due to invalid IL or missing references)
			//IL_085d: Unknown result type (might be due to invalid IL or missing references)
			//IL_08a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_088b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0890: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0909: Unknown result type (might be due to invalid IL or missing references)
			//IL_0938: Unknown result type (might be due to invalid IL or missing references)
			//IL_094b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0952: Unknown result type (might be due to invalid IL or missing references)
			//IL_095e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0970: Unknown result type (might be due to invalid IL or missing references)
			//IL_097c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0981: Unknown result type (might be due to invalid IL or missing references)
			string scriptName = Path.GetFileName(scriptPath);
			LuaState lua = LuaState.Create();
			try
			{
				OpenLibsExtensions.OpenBasicLibrary(lua);
				OpenLibsExtensions.OpenStringLibrary(lua);
				OpenLibsExtensions.OpenTableLibrary(lua);
				OpenLibsExtensions.OpenMathLibrary(lua);
				OpenLibsExtensions.OpenBitwiseLibrary(lua);
				lua.Environment[LuaValue.op_Implicit("loadfile")] = default(LuaValue);
				lua.Environment[LuaValue.op_Implicit("dofile")] = default(LuaValue);
				lua.Environment[LuaValue.op_Implicit("about")] = LuaValue.op_Implicit("baer1.ShipSort v5.1.3");
				lua.Environment[LuaValue.op_Implicit("script")] = LuaValue.op_Implicit(scriptName);
				lua.Environment[LuaValue.op_Implicit("version_major")] = LuaValue.op_Implicit((double)VERSION.Major);
				lua.Environment[LuaValue.op_Implicit("version_minor")] = LuaValue.op_Implicit((double)VERSION.Minor);
				lua.Environment[LuaValue.op_Implicit("version_patch")] = LuaValue.op_Implicit((double)VERSION.Build);
				lua.Environment[LuaValue.op_Implicit("args")] = LuaValue.op_Implicit(SortAPI.LuaTable(args.Select((Func<string, LuaValue>)((string i) => new LuaValue(i))).ToArray()));
				lua.Environment[LuaValue.op_Implicit("expect_version")] = LuaValue.op_Implicit(new LuaFunction((Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)expect_version));
				lua.Environment[LuaValue.op_Implicit("print")] = LuaValue.op_Implicit(new LuaFunction((Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)print));
				lua.Environment[LuaValue.op_Implicit("error")] = LuaValue.op_Implicit(new LuaFunction((Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)error));
				lua.Environment[LuaValue.op_Implicit("raycast")] = LuaValue.op_Implicit(new LuaFunction((Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)raycast));
				lua.Environment[LuaValue.op_Implicit("transform")] = LuaValue.op_Implicit(new LuaFunction((Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)transform));
				lua.Environment[LuaValue.op_Implicit("Vector3")] = new Vector3(Vector3.zero);
				lua.Environment[LuaValue.op_Implicit("ItemPos")] = new ItemPos(new Vector3(Vector3.zero));
				lua.Environment[LuaValue.op_Implicit("RaycastPos")] = new RaycastPos(new Vector3(Vector3.zero));
				AddEnum(lua, typeof(SortAPI.UNLOCKABLE), indexEnum: true);
				AddEnum(lua, typeof(SortAPI.PARENT), indexEnum: false);
				AddEnum(lua, typeof(SortAPI.RELATIVE), indexEnum: false);
				AddEnum(lua, typeof(SortAPI.ROTATE), indexEnum: false);
				AddEnum(lua, typeof(SortAPI.TRANSFORM), indexEnum: false);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_ZERO")] = new Vector3(Vector3.zero);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_ONE")] = new Vector3(Vector3.one);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_DOWN")] = new Vector3(Vector3.down);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_UP")] = new Vector3(Vector3.up);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_LEFT")] = new Vector3(Vector3.left);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_RIGHT")] = new Vector3(Vector3.right);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_FORWARD")] = new Vector3(Vector3.forward);
				lua.Environment[LuaValue.op_Implicit("VECTOR3_BACK")] = new Vector3(Vector3.back);
				lua.Environment[LuaValue.op_Implicit("items")] = LuaValue.op_Implicit(SortAPI.LuaItems(items));
				lua.Environment[LuaValue.op_Implicit("moon")] = LuaValue.op_Implicit(SortAPI.LuaMoon(currentLevel));
				lua.Environment[LuaValue.op_Implicit("remaining_days")] = LuaValue.op_Implicit((double)daysUntilDeadline);
				lua.Environment[LuaValue.op_Implicit("unlockables")] = LuaValue.op_Implicit(SortAPI.LuaUnlockables(cruiser, lights, unlockablesList));
				DateTime utcNow = DateTime.UtcNow;
				CancellationTokenSource cancellationToken = new CancellationTokenSource();
				Task<LuaValue[]> task = Task.Run(async () => await LuaStateExtensions.DoStringAsync(lua, scriptContent, scriptName, cancellationToken.Token));
				try
				{
					int num = Instance.Timeout;
					if (num > 0)
					{
						if (!task.Wait(new TimeSpan(0, 0, num)))
						{
							cancellationToken.Cancel();
							throw new TimeoutException();
						}
					}
					else
					{
						task.Wait();
					}
				}
				catch (AggregateException ex)
				{
					if (ex.InnerExceptions.Count == 1)
					{
						throw ex.InnerException;
					}
					throw;
				}
				DateTime utcNow2 = DateTime.UtcNow;
				LuaValue[] result = task.Result;
				uint num2 = 0u;
				uint num3 = 0u;
				uint num4 = 0u;
				switch (result.Length)
				{
				case 0:
					Chat.Print("No items sorted", (Color?)null);
					break;
				case 1:
				{
					LuaTable val = default(LuaTable);
					if (!((LuaValue)(ref result[0])).TryRead<LuaTable>(ref val))
					{
						throw new ArgumentException("expected table return value, got " + ((LuaValue)(ref result[0])).TypeToString());
					}
					LuaValue val2 = default(LuaValue);
					ItemPos itemPos = default(ItemPos);
					Vector3 position = default(Vector3);
					for (int num5 = 1; num5 <= items.Length; num5++)
					{
						if (!val.TryGetValue(LuaValue.op_Implicit((double)num5), ref val2))
						{
							num4++;
							continue;
						}
						if (!((LuaValue)(ref val2)).TryRead<ItemPos>(ref itemPos))
						{
							if (!((LuaValue)(ref val2)).TryRead<Vector3>(ref position))
							{
								Logger.LogError((object)string.Format("expected {0} or {1} at #{2}, got {3}", "ItemPos", "Vector3", num5, ((LuaValue)(ref val2)).TypeToString()));
								num3++;
								continue;
							}
							itemPos = new ItemPos(position);
						}
						bool transformDirection;
						Transform val3 = GetTransform((SortAPI.TRANSFORM)itemPos.ParentTo, out transformDirection);
						if ((Object)(object)val3 == (Object)null)
						{
							Logger.LogError((object)$"null parent at #{num5}: {itemPos.ParentTo}");
							num3++;
							continue;
						}
						Transform val4 = GetTransform(SortAPI.ToTransform(itemPos.ParentTo, itemPos.RelativeTo), out transformDirection);
						if ((Object)(object)val4 == (Object)null)
						{
							Logger.LogError((object)$"null relative at #{num5}: {itemPos.RelativeTo}");
							num3++;
							continue;
						}
						GrabbableObject val5 = items[num5 - 1];
						if (num2++ == 0)
						{
							player.DropAllHeldItemsAndSyncNonexact();
						}
						string text = itemPos.Position.GetError();
						if (!string.IsNullOrWhiteSpace(text))
						{
							Logger.LogError((object)$"Invalid position at #{num5}: {text}");
							num3++;
							continue;
						}
						Vector3 val6 = val3.InverseTransformPoint(((itemPos.RelativeTo != SortAPI.RELATIVE.Parent) ? val4.TransformPoint((Vector3)itemPos.Position) : val3.TransformPoint((Vector3)itemPos.Position)) + (((Object)(object)val5.itemProperties != (Object)null) ? ((val5.itemProperties.verticalOffset - 0.02f) * Vector3.up) : (0.02f * Vector3.down)));
						int num6 = itemPos.RotationMode switch
						{
							SortAPI.ROTATE.Local => (itemPos.Rotation + Mathf.RoundToInt(val4.eulerAngles.y)) % 360, 
							SortAPI.ROTATE.Parent => (itemPos.Rotation + Mathf.RoundToInt(val3.eulerAngles.y)) % 360, 
							SortAPI.ROTATE.World => itemPos.Rotation, 
							_ => -1, 
						};
						player.SetObjectAsNoLongerHeld(true, true, val6, val5, num6);
						player.ThrowObjectServerRpc(NetworkObjectReference.op_Implicit(((NetworkBehaviour)val5).NetworkObject), true, true, val6, num6);
						player.PlaceGrabbableObject(val3, val6, false, val5);
						player.PlaceObjectServerRpc(NetworkObjectReference.op_Implicit(((NetworkBehaviour)val5).NetworkObject), NetworkObjectReference.op_Implicit(((Component)val3).gameObject), val6, false);
						val5.rotateObject = itemPos.ParentTo == SortAPI.PARENT.Microwave;
					}
					DateTime utcNow3 = DateTime.UtcNow;
					Logger.LogDebug((object)("startTime:" + utcNow.ToString("o", CultureInfo.InvariantCulture) + " scriptEndTime:" + utcNow2.ToString("o", CultureInfo.InvariantCulture) + " sortEndTime:" + utcNow3.ToString("o", CultureInfo.InvariantCulture)));
					Logger.LogInfo((object)("Script execution took " + (utcNow2 - utcNow).ToReadableString() + ", sorting took " + (utcNow3 - utcNow2).ToReadableString()));
					Chat.Print($"Sorted {num2}/{items.Length + skipped} in {(utcNow3 - utcNow).ToReadableString()}", (Color?)null);
					if (num3 != 0)
					{
						Chat.PrintWarning($"{num3} items couldn't be sorted");
					}
					SortStatusCommand.PrevSort = new SortStatusCommand.PreviousSort(DateTime.UtcNow, utcNow3 - utcNow, num2, (uint)items.Length + skipped, isAutoSort, scriptName);
					break;
				}
				default:
					throw new ArgumentException("expected single return value, got multiple");
				}
			}
			finally
			{
				if (lua != null)
				{
					((IDisposable)lua).Dispose();
				}
			}
		}

		private static ValueTask<int> expect_version(LuaFunctionExecutionContext ctx, CancellationToken cancellationToken)
		{
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			switch (((LuaFunctionExecutionContext)(ref ctx)).ArgumentCount)
			{
			case 1:
			{
				int argument = ((LuaFunctionExecutionContext)(ref ctx)).GetArgument<int>(0);
				if (argument < 0)
				{
					throw new ArgumentOutOfRangeException();
				}
				if (VERSION.Major > argument)
				{
					Chat.PrintWarning($"Version conflict (Script is outdated: expected v{argument}, currently v{VERSION.Major})");
				}
				else if (VERSION.Major < argument)
				{
					Chat.PrintWarning($"Version conflict (Mod is outdated: expected v{argument}, currently v{VERSION.Major})");
				}
				break;
			}
			case 2:
			{
				int argument = ((LuaFunctionExecutionContext)(ref ctx)).GetArgument<int>(0);
				int argument2 = ((LuaFunctionExecutionContext)(ref ctx)).GetArgument<int>(1);
				if (argument < 0 || argument2 < 0)
				{
					throw new ArgumentOutOfRangeException();
				}
				if (VERSION.Major < argument)
				{
					Chat.PrintWarning($"Version conflict (Mod is outdated: expected v{argument}, currently v{VERSION.Major})");
				}
				else if (VERSION.Major > argument)
				{
					Chat.PrintWarning($"Version conflict (Script is outdated: expected v{argument}, currently v{VERSION.Major})");
				}
				else if (VERSION.Minor < argument2)
				{
					Chat.PrintWarning($"Version conflict (Mod is outdated: expected at least v{argument}.{argument2}, currently v{VERSION.Major}.{VERSION.Minor})");
				}
				break;
			}
			default:
				throw new ArgumentException();
			}
			((LuaFunctionExecutionContext)(ref ctx)).State.Environment[LuaValue.op_Implicit("expect_version")] = default(LuaValue);
			return new ValueTask<int>(0);
		}

		private static ValueTask<int> print(LuaFunctionExecutionContext ctx, CancellationToken cancellationToken)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			ReadOnlySpan<LuaValue> arguments = ((LuaFunctionExecutionContext)(ref ctx)).Arguments;
			for (int i = 0; i < arguments.Length; i++)
			{
				stringBuilder.Append(" " + ((object)arguments[i]/*cast due to .constrained prefix*/).ToString());
			}
			Logger.LogInfo((object)$"(Script){stringBuilder}");
			return new ValueTask<int>(0);
		}

		private static ValueTask<int> error(LuaFunctionExecutionContext ctx, CancellationToken cancellationToken)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (((LuaFunctionExecutionContext)(ref ctx)).ArgumentCount <= 0)
			{
				throw new Exception();
			}
			StringBuilder stringBuilder = new StringBuilder();
			ReadOnlySpan<LuaValue> arguments = ((LuaFunctionExecutionContext)(ref ctx)).Arguments;
			for (int i = 0; i < arguments.Length; i++)
			{
				stringBuilder.Append(" " + ((object)arguments[i]/*cast due to .constrained prefix*/).ToString());
			}
			throw new Exception(stringBuilder.ToString());
		}

		private static ValueTask<int> raycast(LuaFunctionExecutionContext ctx, CancellationToken cancellationToken)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			LuaValue val;
			RaycastPos raycastPos = default(RaycastPos);
			Vector3 position = default(Vector3);
			switch (((LuaFunctionExecutionContext)(ref ctx)).ArgumentCount)
			{
			case 1:
				val = ((LuaFunctionExecutionContext)(ref ctx)).Arguments[0];
				if (!((LuaValue)(ref val)).TryRead<RaycastPos>(ref raycastPos))
				{
					if (!((LuaValue)(ref val)).TryRead<Vector3>(ref position))
					{
						throw new ArgumentException();
					}
					raycastPos = new RaycastPos(position);
				}
				break;
			case 2:
			{
				if (!((LuaValue)(ref ((LuaFunctionExecutionContext)(ref ctx)).Arguments[0])).TryRead<Vector3>(ref position))
				{
					throw new ArgumentException();
				}
				val = ((LuaFunctionExecutionContext)(ref ctx)).Arguments[1];
				Vector3 direction = default(Vector3);
				if (((LuaValue)(ref val)).TryRead<Vector3>(ref direction))
				{
					raycastPos = new RaycastPos(position, direction);
					break;
				}
				int num = default(int);
				if (((LuaValue)(ref val)).TryRead<int>(ref num))
				{
					if (!Enum.IsDefined(typeof(SortAPI.TRANSFORM), num))
					{
						throw new ArgumentOutOfRangeException();
					}
					raycastPos = new RaycastPos(position, null, (SortAPI.TRANSFORM)num);
					break;
				}
				throw new ArgumentException();
			}
			default:
				throw new ArgumentException();
			}
			bool transformDirection;
			Transform val2 = GetTransform(raycastPos.RelativeTo, out transformDirection);
			if ((Object)(object)val2 == (Object)null)
			{
				Logger.LogError((object)$"null relative for raycast: {raycastPos.RelativeTo}\n{((LuaFunctionExecutionContext)(ref ctx)).State.GetTraceback()}");
			}
			else
			{
				Vector3 val3 = val2.TransformPoint((Vector3)raycastPos.Position);
				Vector3 val4 = (transformDirection ? val2.TransformDirection((Vector3)raycastPos.Direction) : ((Vector3)raycastPos.Direction));
				RaycastHit val5 = default(RaycastHit);
				if (Physics.Raycast(val3, val4, ref val5, 80f, 268437761, (QueryTriggerInteraction)1))
				{
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref ctx)).Return((LuaValue)new Vector3(val2.InverseTransformPoint(((RaycastHit)(ref val5)).point + 0.02f * Vector3.up))));
				}
			}
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref ctx)).Return(default(LuaValue)));
		}

		private static ValueTask<int> transform(LuaFunctionExecutionContext ctx, CancellationToken cancellationToken)
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			if (((LuaFunctionExecutionContext)(ref ctx)).ArgumentCount != 3)
			{
				throw new ArgumentException();
			}
			Vector3 vector = default(Vector3);
			int num = default(int);
			int num2 = default(int);
			if (!((LuaValue)(ref ((LuaFunctionExecutionContext)(ref ctx)).Arguments[0])).TryRead<Vector3>(ref vector) || !((LuaValue)(ref ((LuaFunctionExecutionContext)(ref ctx)).Arguments[1])).TryRead<int>(ref num) || !((LuaValue)(ref ((LuaFunctionExecutionContext)(ref ctx)).Arguments[2])).TryRead<int>(ref num2))
			{
				throw new ArgumentException();
			}
			if (!Enum.IsDefined(typeof(SortAPI.TRANSFORM), num) || !Enum.IsDefined(typeof(SortAPI.TRANSFORM), num2))
			{
				throw new ArgumentOutOfRangeException();
			}
			bool transformDirection;
			Transform val = GetTransform((SortAPI.TRANSFORM)num, out transformDirection);
			if ((Object)(object)val == (Object)null)
			{
				Logger.LogError((object)$"null from for transform: {(SortAPI.TRANSFORM)num}\n{((LuaFunctionExecutionContext)(ref ctx)).State.GetTraceback()}");
				return new ValueTask<int>(((LuaFunctionExecutionContext)(ref ctx)).Return(default(LuaValue)));
			}
			Transform val2 = GetTransform((SortAPI.TRANSFORM)num2, out transformDirection);
			if ((Object)(object)val2 == (Object)null)
			{
				Logger.LogError((object)$"null to for transform: {(SortAPI.TRANSFORM)num2}\n{((LuaFunctionExecutionContext)(ref ctx)).State.GetTraceback()}");
				return new ValueTask<int>(((LuaFunctionExecutionContext)(ref ctx)).Return(default(LuaValue)));
			}
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref ctx)).Return((LuaValue)new Vector3(val2.InverseTransformPoint(val.TransformPoint((Vector3)vector)))));
		}

		private static void AddEnum(LuaState lua, Type enumType, bool indexEnum)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			string arg = enumType.Name.ToUpperInvariant();
			StringBuilder stringBuilder = new StringBuilder();
			foreach (object value in Enum.GetValues(enumType))
			{
				string name = Enum.GetName(enumType, value);
				if (name.StartsWith('_'))
				{
					continue;
				}
				stringBuilder.Append(char.ToUpperInvariant(name[0]));
				string text = name.Substring(1);
				foreach (char c in text)
				{
					if (char.IsUpper(c))
					{
						stringBuilder.Append('_');
					}
					stringBuilder.Append(char.ToUpperInvariant(c));
				}
				lua.Environment[LuaValue.op_Implicit($"{arg}_{stringBuilder}")] = LuaValue.op_Implicit((double)((int)value + (indexEnum ? 1 : 0)));
				stringBuilder.Clear();
			}
		}

		internal static Transform? GetTransform(SortAPI.TRANSFORM transform, out bool transformDirection)
		{
			transformDirection = false;
			switch (transform)
			{
			case SortAPI.TRANSFORM.Ship:
				transformDirection = true;
				return GameObject.Find("/Environment/HangarShip").transform;
			case SortAPI.TRANSFORM.World:
				return GameObject.Find("/Environment").transform;
			case SortAPI.TRANSFORM.Cruiser:
			{
				transformDirection = true;
				VehicleController obj17 = Object.FindFirstObjectByType<VehicleController>();
				if (obj17 == null)
				{
					return null;
				}
				return ((Component)obj17).transform;
			}
			case SortAPI.TRANSFORM.Teleporter:
			{
				GameObject obj2 = GameObject.Find("/Teleporter(Clone)");
				if (obj2 == null)
				{
					return null;
				}
				return obj2.transform;
			}
			case SortAPI.TRANSFORM.Television:
			{
				GameObject obj12 = GameObject.Find("/TelevisionContainer(Clone)");
				if (obj12 == null)
				{
					return null;
				}
				return obj12.transform;
			}
			case SortAPI.TRANSFORM.Cupboard:
				return GameObject.Find("/Environment/HangarShip/StorageCloset").transform;
			case SortAPI.TRANSFORM.FileCabinet:
				return GameObject.Find("/Environment/HangarShip/FileCabinet").transform;
			case SortAPI.TRANSFORM.Toilet:
			{
				GameObject obj21 = GameObject.Find("/Toilet(Clone)");
				if (obj21 == null)
				{
					return null;
				}
				return obj21.transform;
			}
			case SortAPI.TRANSFORM.Shower:
			{
				GameObject obj14 = GameObject.Find("/Shower(Clone)");
				if (obj14 == null)
				{
					return null;
				}
				return obj14.transform;
			}
			case SortAPI.TRANSFORM.RecordPlayer:
			{
				GameObject obj9 = GameObject.Find("/RecordPlayerContainer(Clone)");
				if (obj9 == null)
				{
					return null;
				}
				return obj9.transform;
			}
			case SortAPI.TRANSFORM.Table:
			{
				GameObject obj3 = GameObject.Find("/NormalTableContainer(Clone)");
				if (obj3 == null)
				{
					return null;
				}
				return obj3.transform;
			}
			case SortAPI.TRANSFORM.RomanticTable:
			{
				GameObject obj20 = GameObject.Find("/RomanticTableContainer(Clone)");
				if (obj20 == null)
				{
					return null;
				}
				return obj20.transform;
			}
			case SortAPI.TRANSFORM.Bunkbeds:
				return GameObject.Find("/Environment/HangarShip/Bunkbeds").transform;
			case SortAPI.TRANSFORM.Terminal:
				return GameObject.Find("/Environment/HangarShip/Terminal").transform;
			case SortAPI.TRANSFORM.SignalTranslator:
			{
				GameObject obj15 = GameObject.Find("/SignalTranslator(Clone)");
				if (obj15 == null)
				{
					return null;
				}
				return obj15.transform;
			}
			case SortAPI.TRANSFORM.LoudHorn:
			{
				GameObject obj11 = GameObject.Find("/ShipHorn(Clone)");
				if (obj11 == null)
				{
					return null;
				}
				return obj11.transform;
			}
			case SortAPI.TRANSFORM.InverseTeleporter:
			{
				GameObject obj7 = GameObject.Find("/InverseTeleporter(Clone)");
				if (obj7 == null)
				{
					return null;
				}
				return obj7.transform;
			}
			case SortAPI.TRANSFORM.JackOLantern:
			{
				GameObject obj5 = GameObject.Find("/PumpkinUnlockableContainer(Clone)");
				if (obj5 == null)
				{
					return null;
				}
				return obj5.transform;
			}
			case SortAPI.TRANSFORM.WelcomeMat:
			{
				GameObject obj22 = GameObject.Find("/WelcomeMatContainer(Clone)");
				if (obj22 == null)
				{
					return null;
				}
				return obj22.transform;
			}
			case SortAPI.TRANSFORM.Goldfish:
			{
				GameObject obj19 = GameObject.Find("/FishBowlContainer(Clone)");
				if (obj19 == null)
				{
					return null;
				}
				return obj19.transform;
			}
			case SortAPI.TRANSFORM.PlushiePajamaMan:
			{
				GameObject obj18 = GameObject.Find("/PlushiePJManContainer(Clone)");
				if (obj18 == null)
				{
					return null;
				}
				return obj18.transform;
			}
			case SortAPI.TRANSFORM.DiscoBall:
			{
				GameObject obj16 = GameObject.Find("/DiscoBallContainer(Clone)");
				if (obj16 == null)
				{
					return null;
				}
				return obj16.transform;
			}
			case SortAPI.TRANSFORM.Microwave:
			{
				GameObject obj13 = GameObject.Find("/MicrowaveContainer(Clone)");
				if (obj13 == null)
				{
					return null;
				}
				return obj13.transform;
			}
			case SortAPI.TRANSFORM.SofaChair:
			{
				GameObject obj10 = GameObject.Find("/SofaChairContainer(Clone)");
				if (obj10 == null)
				{
					return null;
				}
				return obj10.transform;
			}
			case SortAPI.TRANSFORM.Fridge:
			{
				GameObject obj8 = GameObject.Find("/FridgeContainer(Clone)");
				if (obj8 == null)
				{
					return null;
				}
				return obj8.transform;
			}
			case SortAPI.TRANSFORM.ClassicPainting:
			{
				GameObject obj6 = GameObject.Find("/ClassicPaintingContainer(Clone)");
				if (obj6 == null)
				{
					return null;
				}
				return obj6.transform;
			}
			case SortAPI.TRANSFORM.ElectricChair:
			{
				GameObject obj4 = GameObject.Find("/ElectricChair(Clone)");
				if (obj4 == null)
				{
					return null;
				}
				return obj4.transform;
			}
			case SortAPI.TRANSFORM.DogHouse:
			{
				GameObject obj = GameObject.Find("/DogHouse(Clone)");
				if (obj == null)
				{
					return null;
				}
				return obj.transform;
			}
			default:
				throw new ArgumentOutOfRangeException();
			}
		}
	}
	public static class SortAPI
	{
		public enum UNLOCKABLE
		{
			Cruiser = -1,
			OrangeSuit,
			GreenSuit,
			HazardSuit,
			PajamaSuit,
			CozyLights,
			Teleporter,
			Television,
			Cupboard,
			FileCabinet,
			Toilet,
			Shower,
			Lights,
			RecordPlayer,
			Table,
			RomanticTable,
			Bunkbeds,
			_Terminal,
			SignalTranslator,
			LoudHorn,
			InverseTeleporter,
			JackOLantern,
			WelcomeMat,
			Goldfish,
			PlushiePajamaMan,
			PurpleSuit,
			BeeSuit,
			BunnySuit,
			DiscoBall,
			Microwave,
			SofaChair,
			Fridge,
			ClassicPainting,
			ElectricChair,
			DogHouse
		}

		public enum TRANSFORM
		{
			Ship = 0,
			World = 1,
			Cupboard = 7,
			Cruiser = -1,
			Fridge = 30,
			Microwave = 28,
			Teleporter = 5,
			Television = 6,
			FileCabinet = 8,
			Toilet = 9,
			Shower = 10,
			RecordPlayer = 12,
			Table = 13,
			RomanticTable = 14,
			Bunkbeds = 15,
			Terminal = 16,
			SignalTranslator = 17,
			LoudHorn = 18,
			InverseTeleporter = 19,
			JackOLantern = 20,
			WelcomeMat = 21,
			Goldfish = 22,
			PlushiePajamaMan = 23,
			DiscoBall = 27,
			SofaChair = 29,
			ClassicPainting = 31,
			ElectricChair = 32,
			DogHouse = 33
		}

		public enum PARENT
		{
			Ship = 0,
			Cupboard = 7,
			Cruiser = -1,
			Fridge = 30,
			Microwave = 28
		}

		public enum RELATIVE
		{
			Parent = 0,
			World = 1,
			Teleporter = 5,
			Television = 6,
			FileCabinet = 8,
			Toilet = 9,
			Shower = 10,
			RecordPlayer = 12,
			Table = 13,
			RomanticTable = 14,
			Bunkbeds = 15,
			Terminal = 16,
			SignalTranslator = 17,
			LoudHorn = 18,
			InverseTeleporter = 19,
			JackOLantern = 20,
			WelcomeMat = 21,
			Goldfish = 22,
			PlushiePajamaMan = 23,
			DiscoBall = 27,
			SofaChair = 29,
			ClassicPainting = 31,
			ElectricChair = 32,
			DogHouse = 33
		}

		public enum ROTATE
		{
			Local,
			Parent,
			World,
			None
		}

		private struct _Item
		{
			public string Name;

			public string Type;

			public bool Large;

			public bool Scrap;

			public LuaValue Arg;

			public int Value;

			public int Index;
		}

		public const string ENV_ABOUT = "about";

		public const string ENV_SCRIPT = "script";

		public const string ENV_VERSION_MAJOR = "version_major";

		public const string ENV_VERSION_MINOR = "version_minor";

		public const string ENV_VERSION_PATCH = "version_patch";

		public const string ENV_ARGS = "args";

		public const string ENV_ITEMS = "items";

		public const string ENV_MOON = "moon";

		public const string ENV_DAYS_LEFT = "remaining_days";

		public const string ENV_UNLOCKABLES = "unlockables";

		public const string ITEM_NAME = "name";

		public const string ITEM_TYPE = "type";

		public const string ITEM_SCRAP = "scrap";

		public const string ITEM_LARGE = "large";

		public const string ITEM_ARG = "arg";

		public const string ITEM_VALUE = "value";

		public const string ITEM_TYPE_INDEX = "index";

		public const string ITEM_TYPE_COUNT = "count";

		public const string MOON_ID = "id";

		public const string MOON_NAME = "name";

		public const string MOON_SCENE_NAME = "scene";

		public const string VECTOR3_ZERO = "VECTOR3_ZERO";

		public const string VECTOR3_ONE = "VECTOR3_ONE";

		public const string VECTOR3_DOWN = "VECTOR3_DOWN";

		public const string VECTOR3_UP = "VECTOR3_UP";

		public const string VECTOR3_LEFT = "VECTOR3_LEFT";

		public const string VECTOR3_RIGHT = "VECTOR3_RIGHT";

		public const string VECTOR3_FORWARD = "VECTOR3_FORWARD";

		public const string VECTOR3_BACK = "VECTOR3_BACK";

		public static string ItemName(GrabbableObject item)
		{
			string name = ((Object)((Component)item).gameObject).name;
			if (!name.EndsWith("(Clone)"))
			{
				return name;
			}
			string text = name;
			int length = "(Clone)".Length;
			return text.Substring(0, text.Length - length);
		}

		public static bool ItemLarge(GrabbableObject item)
		{
			return item.itemProperties?.twoHanded ?? false;
		}

		public static bool ItemScrap(GrabbableObject item)
		{
			Item itemProperties = item.itemProperties;
			return itemProperties == null || itemProperties.isScrap;
		}

		public static LuaValue ItemArg(GrabbableObject item)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			ShotgunItem val = (ShotgunItem)(object)((item is ShotgunItem) ? item : null);
			if (val == null)
			{
				StunGrenadeItem val2 = (StunGrenadeItem)(object)((item is StunGrenadeItem) ? item : null);
				if (val2 == null)
				{
					TetraChemicalItem val3 = (TetraChemicalItem)(object)((item is TetraChemicalItem) ? item : null);
					if (val3 == null)
					{
						RadarBoosterItem val4 = (RadarBoosterItem)(object)((item is RadarBoosterItem) ? item : null);
						if (val4 == null)
						{
							JetpackItem val5 = (JetpackItem)(object)((item is JetpackItem) ? item : null);
							if (val5 == null)
							{
								SprayPaintItem val6 = (SprayPaintItem)(object)((item is SprayPaintItem) ? item : null);
								if (val6 == null)
								{
									BeltBagItem val7 = (BeltBagItem)(object)((item is BeltBagItem) ? item : null);
									if (val7 != null)
									{
										return LuaValue.op_Implicit((double)val7.objectsInBag.Count);
									}
									return default(LuaValue);
								}
								return LuaValue.op_Implicit((double)val6.sprayCanTank);
							}
							return LuaValue.op_Implicit(val5.jetpackBroken);
						}
						return LuaValue.op_Implicit(val4.radarEnabled);
					}
					return LuaValue.op_Implicit((double)val3.fuel);
				}
				return LuaValue.op_Implicit(val2.hasExploded);
			}
			return LuaValue.op_Implicit((double)val.shellsLoaded);
		}

		public static LuaTable LuaItems(GrabbableObject[] items)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			_Item[] array = new _Item[items.Length];
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			for (int i = 0; i < items.Length; i++)
			{
				GrabbableObject val = items[i];
				string text = ItemName(val);
				int num = i;
				_Item item = new _Item
				{
					Name = text,
					Type = ((object)val).GetType().Name,
					Large = ItemLarge(val),
					Scrap = ItemScrap(val),
					Arg = ItemArg(val),
					Value = val.scrapValue
				};
				int index;
				if (!dictionary.ContainsKey(text))
				{
					int num2 = (dictionary[text] = 1);
					index = num2;
				}
				else
				{
					index = ++dictionary[text];
				}
				item.Index = index;
				array[num] = item;
			}
			LuaTable val2 = new LuaTable(items.Length, 0);
			for (int j = 0; j < array.Length; j++)
			{
				_Item item2 = array[j];
				val2[LuaValue.op_Implicit((double)(j + 1))] = LuaValue.op_Implicit(new LuaTable
				{
					[LuaValue.op_Implicit("name")] = LuaValue.op_Implicit(item2.Name),
					[LuaValue.op_Implicit("type")] = LuaValue.op_Implicit(item2.Type),
					[LuaValue.op_Implicit("scrap")] = LuaValue.op_Implicit(item2.Scrap),
					[LuaValue.op_Implicit("large")] = LuaValue.op_Implicit(item2.Large),
					[LuaValue.op_Implicit("arg")] = item2.Arg,
					[LuaValue.op_Implicit("value")] = LuaValue.op_Implicit((double)item2.Value),
					[LuaValue.op_Implicit("index")] = LuaValue.op_Implicit((double)item2.Index),
					[LuaValue.op_Implicit("count")] = LuaValue.op_Implicit((double)dictionary[item2.Name])
				});
			}
			return val2;
		}

		public static LuaTable LuaMoon(SelectableLevel level)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			return new LuaTable
			{
				[LuaValue.op_Implicit("id")] = LuaValue.op_Implicit((double)level.levelID),
				[LuaValue.op_Implicit("name")] = LuaValue.op_Implicit(level.PlanetName),
				[LuaValue.op_Implicit("scene")] = LuaValue.op_Implicit(level.sceneName)
			};
		}

		public static LuaTable LuaUnlockables(bool cruiser, bool lights, UnlockablesList unlockablesList)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			LuaTable val = new LuaTable { [LuaValue.op_Implicit(0.0)] = LuaValue.op_Implicit(cruiser) };
			for (int i = 0; i < unlockablesList.unlockables.Count; i++)
			{
				UnlockableItem val3 = unlockablesList.unlockables[i];
				val[LuaValue.op_Implicit((double)(i + 1))] = LuaValue.op_Implicit((val3.alreadyUnlocked || val3.hasBeenUnlockedByPlayer) && !val3.inStorage);
			}
			val[LuaValue.op_Implicit(12.0)] = LuaValue.op_Implicit(lights);
			return val;
		}

		public static LuaTable LuaTable(LuaValue[] list)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			LuaTable val = new LuaTable();
			for (int i = 0; i < list.Length; i++)
			{
				val[LuaValue.op_Implicit((double)(i + 1))] = list[i];
			}
			return val;
		}

		public static TRANSFORM ToTransform(PARENT parent, RELATIVE relative)
		{
			if (relative == RELATIVE.Parent)
			{
				return (TRANSFORM)parent;
			}
			return (TRANSFORM)relative;
		}
	}
	internal static class Utils
	{
		public static string ToReadableString(this TimeSpan timeSpan)
		{
			List<string> list = new List<string>(4);
			TimeSpan timeSpan2 = timeSpan.Duration();
			if (timeSpan2.Days > 0)
			{
				list.Add((timeSpan.Days == 1) ? "1 day" : $"{timeSpan.Days} days");
			}
			if (timeSpan2.Hours > 0)
			{
				list.Add((timeSpan.Hours == 1) ? "1 hour" : $"{timeSpan.Hours} hours");
			}
			if (timeSpan2.Minutes > 0)
			{
				list.Add((timeSpan.Minutes == 1) ? "1 minute" : $"{timeSpan.Minutes} minutes");
			}
			if (timeSpan2.Seconds > 0)
			{
				list.Add((timeSpan.Seconds == 1) ? "1 second" : $"{timeSpan.Seconds} seconds");
			}
			if (list.Count > 0)
			{
				return string.Join(", ", list);
			}
			return "<1 second";
		}

		public static string BytesToString(int bytes)
		{
			if (bytes < 1048576)
			{
				if (bytes >= 0)
				{
					if (bytes < 1024)
					{
						return $"{bytes} bytes";
					}
					return $"{bytes / 1024}KB";
				}
				throw new ArgumentOutOfRangeException("bytes");
			}
			if (bytes < 1073741824)
			{
				return $"{bytes / 1048576}MB";
			}
			return $"{(float)bytes / 1.0737418E+09f:F2}GB";
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "baer1.ShipSort";

		public const string PLUGIN_NAME = "LethalShipSort";

		public const string PLUGIN_VERSION = "5.1.3";
	}
}
namespace LethalShipSort.Patches
{
	[HarmonyPatch(typeof(NetworkManager), "Awake")]
	internal static class NetworkManager_Awake
	{
		private static void Postfix(ref NetworkManager __instance)
		{
			__instance.OnClientConnectedCallback += NetworkManager_ClientConnected;
		}

		private static void NetworkManager_ClientConnected(ulong clientId)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				LethalShipSort.Logger.LogDebug((object)string.Format(">> {0}({1}: {2})", "NetworkManager_ClientConnected", "clientId", clientId));
				NetworkManager singleton = NetworkManager.Singleton;
				if (clientId != 0L && singleton.IsServer)
				{
					singleton.CustomMessagingManager.SendNamedMessage("baer1.ShipSort", clientId, LethalShipSort.Instance.CreateNetworkMessage(), (NetworkDelivery)4);
				}
			}
			catch (Exception arg)
			{
				LethalShipSort.Logger.LogError((object)$"Error sharing script to {clientId}: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(NetworkManager), "Initialize")]
	internal static class NetworkManager_Initialize
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__NetworkMessageHandler;
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_0039: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			return CodeMatcherExtensions.MatchForward(new CodeMatcher(instructions, (ILGenerator)null), (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.PropertySetter(typeof(NetworkManager), "CustomMessagingManager"), (string)null)
			}).Insert((CodeInstruction[])(object)new CodeInstruction[2]
			{
				new CodeInstruction(OpCodes.Dup, (object)null),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(NetworkManager_Initialize), "RegisterNetworkMessageHandler", (Type[])null, (Type[])null))
			}).InstructionEnumeration();
		}

		private static void RegisterNetworkMessageHandler(CustomMessagingManager customMessagingManager)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			LethalShipSort instance = LethalShipSort.Instance;
			instance.ClearSharedScript();
			object obj = <>O.<0>__NetworkMessageHandler;
			if (obj == null)
			{
				HandleNamedMessageDelegate val = LethalShipSort.NetworkMessageHandler;
				<>O.<0>__NetworkMessageHandler = val;
				obj = (object)val;
			}
			customMessagingManager.RegisterNamedMessageHandler("baer1.ShipSort", (HandleNamedMessageDelegate)obj);
			LethalShipSort.Logger.LogInfo((object)"Registered network message handler");
			instance.ReloadScript();
			SortStatusCommand.PrevSort = null;
		}
	}
	[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
	internal static class RoundManager_DespawnPropsAtEndOfRound
	{
		private static void Postfix(ref RoundManager __instance)
		{
			((MonoBehaviour)__instance.playersManager).StartCoroutine(DelayedAutoSort(__instance.playersManager));
		}

		private static IEnumerator DelayedAutoSort(StartOfRound __instance)
		{
			yield return (object)new WaitForSecondsRealtime(2f);
			LethalShipSort.TryAutoSort(__instance);
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "LoadShipGrabbableItems")]
	internal static class StartOfRound_LoadShipGrabbableItems
	{
		private static void Postfix(ref StartOfRound __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(DelayedAutoSort(__instance));
		}

		private static IEnumerator DelayedAutoSort(StartOfRound __instance)
		{
			yield return (object)new WaitForSecondsRealtime(2f);
			LethalShipSort.TryAutoSort(__instance);
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	internal static class StartOfRound_StartGame
	{
		private static void Prefix(ref StartOfRound __instance)
		{
			LethalShipSort.TryAutoSort(__instance);
		}
	}
}
namespace LethalShipSort.LuaObjects
{
	[LuaObject]
	public class ItemPos : ILuaUserData
	{
		private SortAPI.PARENT parent_to;

		private SortAPI.RELATIVE relative_to;

		private Vector3 position;

		private int rotation;

		private SortAPI.ROTATE rotation_mode;

		private static readonly LuaFunction __metamethod_call = new LuaFunction("call", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			Vector3 argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<Vector3>(1);
			ItemPos itemPos = New(argument, argument2);
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)itemPos)));
		});

		private static readonly LuaFunction __function_with_parent = new LuaFunction("with_parent", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			int argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(1);
			ItemPos itemPos = argument.with_parent(argument2);
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)itemPos)));
		});

		private static readonly LuaFunction __function_with_relative = new LuaFunction("with_relative", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			int argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(1);
			ItemPos itemPos = argument.with_relative(argument2);
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)itemPos)));
		});

		private static readonly LuaFunction __function_with_rotation = new LuaFunction("with_rotation", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			int argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(1);
			ItemPos itemPos = argument.with_rotation(argument2);
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)itemPos)));
		});

		private static readonly LuaFunction __function_with_rotation_mode = new LuaFunction("with_rotation_mode", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			int argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(1);
			ItemPos itemPos = argument.with_rotation_mode(argument2);
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)itemPos)));
		});

		private static readonly LuaFunction __metamethod_tostring = new LuaFunction("tostring", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			string text = argument.ToString();
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit(text)));
		});

		private static readonly LuaFunction __metamethod_index = new LuaFunction("index", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			LuaValue argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument(1);
			string text = default(string);
			return ((LuaValue)(ref argument2)).TryRead<string>(ref text) ? (text switch
			{
				"parent_to" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit((double)argument._ParentTo))), 
				"relative_to" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit((double)argument._RelativeTo))), 
				"position" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)argument.Position))), 
				"rotation" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit((double)argument.Rotation))), 
				"rotation_mode" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit((double)argument._RotationMode))), 
				"with_parent" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(new LuaValue(__function_with_parent))), 
				"with_relative" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(new LuaValue(__function_with_relative))), 
				"with_rotation" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(new LuaValue(__function_with_rotation))), 
				"with_rotation_mode" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(new LuaValue(__function_with_rotation_mode))), 
				_ => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.Nil)), 
			}) : new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.Nil));
		});

		private static readonly LuaFunction __metamethod_newindex = new LuaFunction("newindex", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			ItemPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<ItemPos>(0);
			LuaValue argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument(1);
			string text = default(string);
			if (((LuaValue)(ref argument2)).TryRead<string>(ref text))
			{
				bool flag;
				switch (text)
				{
				case "parent_to":
					argument._ParentTo = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "relative_to":
					argument._RelativeTo = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "position":
					argument.Position = ((LuaFunctionExecutionContext)(ref context)).GetArgument<Vector3>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "rotation":
					argument.Rotation = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "rotation_mode":
					argument._RotationMode = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "with_parent":
				case "with_relative":
				case "with_rotation":
				case "with_rotation_mode":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (flag)
				{
					throw new LuaRuntimeException(((LuaFunctionExecutionContext)(ref context)).State, LuaValue.op_Implicit("'" + text + "' cannot overwrite."), 1);
				}
				throw new LuaRuntimeException(((LuaFunctionExecutionContext)(ref context)).State, LuaValue.op_Implicit("'" + text + "' not found."), 1);
			}
			throw new LuaRuntimeException(((LuaFunctionExecutionContext)(ref context)).State, LuaValue.op_Implicit($"'{argument2}' not found."), 1);
		});

		private static LuaTable? __metatable;

		[LuaMember("parent_to")]
		private int _ParentTo
		{
			get
			{
				return (int)parent_to;
			}
			set
			{
				if (!Enum.IsDefined(typeof(SortAPI.PARENT), value))
				{
					throw new ArgumentOutOfRangeException();
				}
				parent_to = (SortAPI.PARENT)value;
			}
		}

		[LuaMember("relative_to")]
		private int _RelativeTo
		{
			get
			{
				return (int)relative_to;
			}
			set
			{
				if (!Enum.IsDefined(typeof(SortAPI.RELATIVE), value))
				{
					throw new ArgumentOutOfRangeException();
				}
				relative_to = (SortAPI.RELATIVE)value;
			}
		}

		public SortAPI.PARENT ParentTo
		{
			get
			{
				return parent_to;
			}
			set
			{
				parent_to = value;
			}
		}

		public SortAPI.RELATIVE RelativeTo
		{
			get
			{
				return relative_to;
			}
			set
			{
				relative_to = value;
			}
		}

		[LuaMember("position")]
		public Vector3 Position
		{
			get
			{
				return position;
			}
			set
			{
				position = value;
			}
		}

		[LuaMember("rotation")]
		public int Rotation
		{
			get
			{
				return rotation;
			}
			set
			{
				rotation = value % 360;
			}
		}

		[LuaMember("rotation_mode")]
		private int _RotationMode
		{
			get
			{
				return (int)rotation_mode;
			}
			set
			{
				if (!Enum.IsDefined(typeof(SortAPI.ROTATE), value))
				{
					throw new ArgumentOutOfRangeException();
				}
				rotation_mode = (SortAPI.ROTATE)value;
			}
		}

		public SortAPI.ROTATE RotationMode
		{
			get
			{
				return rotation_mode;
			}
			set
			{
				rotation_mode = value;
			}
		}

		LuaTable? ILuaUserData.Metatable
		{
			get
			{
				return Metatable;
			}
			set
			{
				Metatable = value;
			}
		}

		private static LuaTable? Metatable
		{
			get
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Expected O, but got Unknown
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				if (__metatable != null)
				{
					return __metatable;
				}
				__metatable = new LuaTable();
				__metatable[LuaValue.op_Implicit("__call")] = LuaValue.op_Implicit(__metamethod_call);
				__metatable[LuaValue.op_Implicit("__tostring")] = LuaValue.op_Implicit(__metamethod_tostring);
				__metatable[LuaValue.op_Implicit("__index")] = LuaValue.op_Implicit(__metamethod_index);
				__metatable[LuaValue.op_Implicit("__newindex")] = LuaValue.op_Implicit(__metamethod_newindex);
				return __metatable;
			}
			set
			{
				__metatable = value;
			}
		}

		public ItemPos(Vector3 _position, int _rotation = 0, SortAPI.PARENT _parent_to = SortAPI.PARENT.Ship, SortAPI.RELATIVE _relative_to = SortAPI.RELATIVE.Parent, SortAPI.ROTATE _rotation_mode = SortAPI.ROTATE.Local)
		{
			parent_to = _parent_to;
			relative_to = _relative_to;
			position = _position;
			rotation = _rotation;
			rotation_mode = _rotation_mode;
			base..ctor();
		}

		[LuaMetamethod(/*Could not decode attribute arguments.*/)]
		public static ItemPos New(ItemPos _, Vector3 position)
		{
			return new ItemPos(position);
		}

		[LuaMember("with_parent")]
		public ItemPos with_parent(int _parent_to)
		{
			_ParentTo = _parent_to;
			return this;
		}

		[LuaMember("with_relative")]
		public ItemPos with_relative(int _relative_to)
		{
			_RelativeTo = _relative_to;
			return this;
		}

		[LuaMember("with_rotation")]
		public ItemPos with_rotation(int rotation)
		{
			Rotation = rotation;
			return this;
		}

		[LuaMember("with_rotation_mode")]
		public ItemPos with_rotation_mode(int _rotation_mode)
		{
			_RotationMode = _rotation_mode;
			return this;
		}

		[LuaMetamethod(/*Could not decode attribute arguments.*/)]
		public override string ToString()
		{
			object obj = position;
			object obj2 = relative_to;
			SortAPI.ROTATE rOTATE = rotation_mode;
			object obj3 = ((rOTATE != SortAPI.ROTATE.None) ? $"{rotation_mode} deg {rotation}" : ((object)SortAPI.ROTATE.None));
			return $"{obj} rel {obj2} rot {obj3} parent {parent_to}";
		}

		public static implicit operator LuaValue(ItemPos value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return LuaValue.FromUserData((ILuaUserData)(object)value);
		}
	}
	[LuaObject]
	public class RaycastPos : ILuaUserData
	{
		private SortAPI.TRANSFORM relative_to;

		private Vector3 position;

		private Vector3 direction;

		private static readonly LuaFunction __metamethod_call = new LuaFunction("call", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			RaycastPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<RaycastPos>(0);
			Vector3 argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<Vector3>(1);
			Vector3 argument3 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<Vector3>(2);
			int argument4 = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(3);
			RaycastPos raycastPos = New(argument, argument2, argument3, argument4);
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)raycastPos)));
		});

		private static readonly LuaFunction __metamethod_tostring = new LuaFunction("tostring", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			RaycastPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<RaycastPos>(0);
			string text = argument.ToString();
			return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit(text)));
		});

		private static readonly LuaFunction __metamethod_index = new LuaFunction("index", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			RaycastPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<RaycastPos>(0);
			LuaValue argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument(1);
			string text = default(string);
			return ((LuaValue)(ref argument2)).TryRead<string>(ref text) ? (text switch
			{
				"relative_to" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.op_Implicit((double)argument._RelativeTo))), 
				"position" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)argument.Position))), 
				"direction" => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.FromUserData((ILuaUserData)(object)argument.Direction))), 
				_ => new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.Nil)), 
			}) : new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return(LuaValue.Nil));
		});

		private static readonly LuaFunction __metamethod_newindex = new LuaFunction("newindex", (Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>>)delegate(LuaFunctionExecutionContext context, CancellationToken ct)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			RaycastPos argument = ((LuaFunctionExecutionContext)(ref context)).GetArgument<RaycastPos>(0);
			LuaValue argument2 = ((LuaFunctionExecutionContext)(ref context)).GetArgument(1);
			string text = default(string);
			if (((LuaValue)(ref argument2)).TryRead<string>(ref text))
			{
				switch (text)
				{
				case "relative_to":
					argument._RelativeTo = ((LuaFunctionExecutionContext)(ref context)).GetArgument<int>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "position":
					argument.Position = ((LuaFunctionExecutionContext)(ref context)).GetArgument<Vector3>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				case "direction":
					argument.Direction = ((LuaFunctionExecutionContext)(ref context)).GetArgument<Vector3>(2);
					return new ValueTask<int>(((LuaFunctionExecutionContext)(ref context)).Return());
				default:
					throw new LuaRuntimeException(((LuaFunctionExecutionContext)(ref context)).State, LuaValue.op_Implicit("'" + text + "' not found."), 1);
				}
			}
			throw new LuaRuntimeException(((LuaFunctionExecutionContext)(ref context)).State, LuaValue.op_Implicit($"'{argument2}' not found."), 1);
		});

		private static LuaTable? __metatable;

		[LuaMember("relative_to")]
		private int _RelativeTo
		{
			get
			{
				return (int)relative_to;
			}
			set
			{
				if (!Enum.IsDefined(typeof(SortAPI.TRANSFORM), value))
				{
					throw new ArgumentOutOfRangeException();
				}
				relative_to = (SortAPI.TRANSFORM)value;
			}
		}

		public SortAPI.TRANSFORM RelativeTo
		{
			get
			{
				return relative_to;
			}
			set
			{
				relative_to = value;
			}
		}

		[LuaMember("position")]
		public Vector3 Position
		{
			get
			{
				return position;
			}
			set
			{
				position = value;
			}
		}

		[LuaMember("direction")]
		public Vector3 Direction
		{
			get
			{
				return direction;
			}
			set
			{
				direction = value;
			}
		}

		LuaTable? ILuaUserData.Metatable
		{
			get
			{
				return Metatable;
			}
			set
			{
				Metatable = value;
			}
		}

		private static LuaTable? Metatable
		{
			get
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Expected O, but got Unknown
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				if (__metatable != null)
				{
					return __metatable;
				}
				__metatable = new LuaTable();
				__metatable[LuaValue.op_Implicit("__call")] = LuaValue.op_Implicit(__metamethod_call);
				__metatable[LuaValue.op_Implicit("__tostring")] = LuaValue.op_Implicit(__metamethod_tostring);
				__metatable[LuaValue.op_Implicit("__index")] = LuaValue.op_Implicit(__metamethod_index);
				__metatable[LuaValue.op_Implicit("__newindex")] = LuaValue.op_Implicit(__metamethod_newindex);
				return __metatable;
			}
			set
			{
				__metatable = value;
			}
		}

		public RaycastPos(Vector3 _position, Vector3? _direction = null, SortAPI.TRANSFORM _relative_to = SortAPI.TRANSFORM.Ship)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			relative_to = _relative_to;
			position = _position;
			direction = _direction ?? new Vector3(Vector3.down);
			base..ctor();
		}

		[LuaMetamethod(/*Could not decode attribute arguments.*/)]
		public static RaycastPos New(RaycastPos _, Vector3 position, Vector3 direction, int relative_to)
		{
			if (!Enum.IsDefined(typeof(SortAPI.TRANSFORM), relative_to))
			{
				throw new ArgumentOutOfRangeException();
			}
			return new RaycastPos(position, direction, (SortAPI.TRANSFORM)

Lua.dll

Decompiled 4 days ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Lua.CodeAnalysis;
using Lua.CodeAnalysis.Compilation;
using Lua.CodeAnalysis.Syntax;
using Lua.CodeAnalysis.Syntax.Nodes;
using Lua.IO;
using Lua.Internal;
using Lua.Internal.CompilerServices;
using Lua.Platforms;
using Lua.Runtime;
using Lua.Standard.Internal;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Lua.Tests")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("nuskey;Akeit0")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Yusuke Nakada")]
[assembly: AssemblyDescription("High performance Lua interpreter implemented in C# for .NET and Unity")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d9fb336931d2dc874c924575cc15d9c2d35841ce")]
[assembly: AssemblyProduct("Lua")]
[assembly: AssemblyTitle("Lua")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/nuskey8/Lua-CSharp")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SetsRequiredMembersAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object?[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = new object[0];
		}

		public StringSyntaxAttribute(string syntax, params object?[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class UnscopedRefAttribute : Attribute
	{
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[]? _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string? s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string? s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			if (_pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresPreviewFeaturesAttribute : Attribute
	{
		public string? Message { get; }

		public string? Url { get; set; }

		public RequiresPreviewFeaturesAttribute()
		{
		}

		public RequiresPreviewFeaturesAttribute(string? message)
		{
			Message = message;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class AsyncMethodBuilderAttribute(Type builderType) : Attribute()
	{
		public Type BuilderType { get; } = builderType;
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CollectionBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public string MethodName { get; }

		public CollectionBuilderAttribute(Type builderType, string methodName)
		{
			BuilderType = builderType;
			MethodName = methodName;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CompilerFeatureRequiredAttribute : Attribute
	{
		public const string RefStructs = "RefStructs";

		public const string RequiredMembers = "RequiredMembers";

		public string FeatureName { get; }

		public bool IsOptional { get; set; }

		public CompilerFeatureRequiredAttribute(string featureName)
		{
			FeatureName = featureName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
	{
		public string[] Arguments { get; }

		public InterpolatedStringHandlerArgumentAttribute(string argument)
		{
			Arguments = new string[1] { argument };
		}

		public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
		{
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerAttribute : Attribute
	{
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ModuleInitializerAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiredMemberAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresLocationAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SkipLocalsInitAttribute : Attribute
	{
	}
}
namespace System.Threading
{
	internal static class CancellationTokenExtensions
	{
		public static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object?> callback, object? state)
		{
			return cancellationToken.Register(callback, state, useSynchronizationContext: false);
		}
	}
}
namespace Lua
{
	public class LuaParseException : Exception
	{
		public string? ChunkName { get; }

		public SourcePosition Position { get; }

		public override string Message => $"{ChunkName}:{Position.Line}: {base.Message}";

		public LuaParseException(string? chunkName, SourcePosition position, string message)
		{
			ChunkName = chunkName;
			Position = position;
			base..ctor(message);
		}

		public static void UnexpectedToken(string? chunkName, SourcePosition position, SyntaxToken token)
		{
			throw new LuaParseException(chunkName, position, $"unexpected symbol <{token.Type}> near '{token.Text}'");
		}

		public static void ExpectedToken(string? chunkName, SourcePosition position, SyntaxTokenType token)
		{
			throw new LuaParseException(chunkName, position, $"'{token}' expected");
		}

		public static void UnfinishedLongComment(string? chunkName, SourcePosition position)
		{
			throw new LuaParseException(chunkName, position, $"unfinished long comment (starting at line {position.Line})");
		}

		public static void SyntaxError(string? chunkName, SourcePosition position, SyntaxToken? token)
		{
			throw new LuaParseException(chunkName, position, "syntax error " + ((!token.HasValue) ? "" : $"near '{token.Value.Text}'"));
		}

		public static void NoVisibleLabel(string label, string? chunkName, SourcePosition position)
		{
			throw new LuaParseException(chunkName, position, "no visible label '" + label + "' for <goto>");
		}

		public static void BreakNotInsideALoop(string? chunkName, SourcePosition position)
		{
			throw new LuaParseException(chunkName, position, "<break> not inside a loop");
		}
	}
	public class LuaCompileException : Exception
	{
		public string ChunkName { get; }

		public int OffSet { get; }

		public SourcePosition Position => <position>P;

		public string MainMessage => <message>P;

		public string? NearToken => <nearToken>P;

		public string MessageWithNearToken => base.Message;

		public override string Message => $"{ChunkName}:{Position.Line}: {base.Message}";

		public LuaCompileException(string chunkName, SourcePosition position, int offset, string message, string? nearToken)
		{
			<position>P = position;
			<message>P = message;
			<nearToken>P = nearToken;
			ChunkName = chunkName;
			OffSet = offset;
			base..ctor(GetMessageWithNearToken(<message>P, <nearToken>P));
		}

		private static string GetMessageWithNearToken(string message, string? nearToken)
		{
			if (string.IsNullOrEmpty(nearToken))
			{
				return message;
			}
			return message + " near " + nearToken;
		}
	}
	public class LuaUndumpException : Exception
	{
		public LuaUndumpException(string message)
			: base(message)
		{
		}
	}
	internal class LuaStackOverflowException : Exception
	{
		public LuaStackOverflowException()
			: base("stack overflow")
		{
		}

		public override string ToString()
		{
			return "stack overflow";
		}
	}
	internal interface ILuaTracebackBuildable
	{
		Traceback? BuildOrGet();
	}
	public class LuaRuntimeException : Exception, ILuaTracebackBuildable
	{
		private int level = 1;

		private Traceback? luaTraceback;

		public Traceback? LuaTraceback
		{
			get
			{
				if (luaTraceback == null)
				{
					((ILuaTracebackBuildable)this).BuildOrGet();
				}
				return luaTraceback;
			}
		}

		internal LuaState? State { get; private set; }

		public LuaValue ErrorObject { get; }

		public override string Message
		{
			get
			{
				if (base.InnerException != null)
				{
					return base.InnerException.Message;
				}
				if (LuaTraceback == null)
				{
					return ErrorObject.ToString();
				}
				return CreateMessage(LuaTraceback, ErrorObject, level);
			}
		}

		public LuaRuntimeException(LuaState? state, Exception innerException)
			: base(innerException.Message, innerException)
		{
			if (state != null)
			{
				state.CurrentException?.BuildOrGet();
				state.ExceptionTrace.Clear();
				state.CurrentException = this;
			}
			State = state;
		}

		public LuaRuntimeException(LuaState? state, LuaValue errorObject, int level = 1)
		{
			if (state != null)
			{
				state.CurrentException?.BuildOrGet();
				state.ExceptionTrace.Clear();
				state.CurrentException = this;
			}
			State = state;
			ErrorObject = errorObject;
			this.level = level;
		}

		public static void AttemptInvalidOperation(LuaState? state, string op, LuaValue a, LuaValue b)
		{
			string text = a.TypeToString();
			string text2 = b.TypeToString();
			if (text == text2)
			{
				throw new LuaRuntimeException(state, "attempt to " + op + " two " + text + " values");
			}
			throw new LuaRuntimeException(state, "attempt to " + op + " a " + text + " value with a " + text2 + " value");
		}

		public static void AttemptInvalidOperation(LuaState? state, string op, LuaValue a)
		{
			throw new LuaRuntimeException(state, "attempt to " + op + " a " + a.TypeToString() + " value");
		}

		internal static void AttemptInvalidOperationOnLuaStack(LuaState state, string op, int lastPc, int regA, int regB)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			LuaValue luaValue = ((regA < 255) ? state.Stack[currentFrame.Base + regA] : ((LuaClosure)currentFrame.Function).Proto.Constants[regA - 256]);
			LuaValue luaValue2 = ((regB < 255) ? state.Stack[currentFrame.Base + regB] : ((LuaClosure)currentFrame.Function).Proto.Constants[regB - 256]);
			LuaFunction function = currentFrame.Function;
			string name2;
			string name = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regA, out name2);
			string name4;
			string name3 = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regB, out name4);
			using PooledList<char> pooledList = new PooledList<char>(64);
			pooledList.Clear();
			pooledList.AddRange("attempt to ");
			pooledList.AddRange(op);
			pooledList.AddRange(" a ");
			pooledList.AddRange(luaValue.TypeToString());
			pooledList.AddRange(" value");
			if (name != null && name2 != null)
			{
				pooledList.AddRange(" (" + name + " '" + name2 + "')");
			}
			pooledList.AddRange(" with a ");
			pooledList.AddRange(luaValue2.TypeToString());
			pooledList.AddRange(" value");
			if (name3 != null && name4 != null)
			{
				pooledList.AddRange(" (" + name3 + " '" + name4 + "')");
			}
			throw new LuaRuntimeException(state, pooledList.AsSpan().ToString());
		}

		internal static void AttemptInvalidOperationOnLuaStack(LuaState state, string op, int lastPc, int reg)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			LuaValue luaValue = ((reg < 255) ? state.Stack[currentFrame.Base + reg] : ((LuaClosure)currentFrame.Function).Proto.Constants[reg - 256]);
			string name2;
			string name = LuaDebug.GetName(((LuaClosure)currentFrame.Function).Proto, lastPc, reg, out name2);
			using PooledList<char> pooledList = new PooledList<char>(64);
			pooledList.Clear();
			pooledList.AddRange("attempt to ");
			pooledList.AddRange(op);
			pooledList.AddRange(" a ");
			pooledList.AddRange(luaValue.TypeToString());
			pooledList.AddRange(" value");
			if (name != null && name2 != null)
			{
				pooledList.AddRange(" (" + name + " '" + name2 + "')");
			}
			throw new LuaRuntimeException(state, pooledList.AsSpan().ToString());
		}

		internal static void AttemptInvalidOperationOnUpValues(LuaState state, string op, int reg)
		{
			LuaClosure obj = (LuaClosure)state.GetCurrentFrame().Function;
			UpValueDesc upValueDesc = obj.Proto.UpValues[reg];
			LuaValue value = obj.UpValues[upValueDesc.Index].GetValue();
			string name = upValueDesc.Name;
			throw new LuaRuntimeException(state, "attempt to " + op + " a " + value.TypeToString() + " value (upvalue '" + name + "')");
		}

		internal static (string NameWhat, string Name) GetCurrentFunctionName(LuaState state)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			int pc = currentFrame.CallerInstructionIndex;
			LuaFunction luaFunction;
			if (currentFrame.IsTailCall)
			{
				pc = state.LastPc;
				luaFunction = state.LastCallerFunction;
			}
			else
			{
				ReadOnlySpan<CallStackFrame> callStackFrames = state.GetCallStackFrames();
				luaFunction = callStackFrames[callStackFrames.Length - 2].Function;
			}
			if (!(luaFunction is LuaClosure luaClosure))
			{
				return (NameWhat: "function", Name: currentFrame.Function.Name);
			}
			string name;
			return (NameWhat: LuaDebug.GetFuncName(luaClosure.Proto, pc, out name) ?? "", Name: name ?? currentFrame.Function.Name);
		}

		public static void BadArgument(LuaState state, int argumentId)
		{
			BadArgument(state, argumentId, "value expected");
		}

		public static void BadArgument(LuaState state, int argumentId, LuaValueType expected, LuaValueType actual)
		{
			BadArgument(state, argumentId, LuaValue.ToString(expected) + " expected, got " + LuaValue.ToString(actual) + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, LuaValueType[] expected, LuaValueType actual)
		{
			BadArgument(state, argumentId, "(" + string.Join(" or ", expected.Select(LuaValue.ToString)) + " expected, got " + LuaValue.ToString(actual) + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, string expected, string actual)
		{
			BadArgument(state, argumentId, "(" + expected + " expected, got " + actual + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, string[] expected, string actual)
		{
			if (expected.Length == 0)
			{
				throw new ArgumentException("Expected array must not be empty", "expected");
			}
			BadArgument(state, argumentId, "(" + string.Join(" or ", expected) + " expected, got " + actual + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, string message)
		{
			var (text, text2) = GetCurrentFunctionName(state);
			if (text == "method")
			{
				argumentId--;
				if (argumentId == 0)
				{
					throw new LuaRuntimeException(state, "calling '" + text2 + "' on bad self (" + message + ")");
				}
			}
			throw new LuaRuntimeException(state, $"bad argument #{argumentId} to '{text2}' ({message})");
		}

		public static void BadArgumentNumberIsNotInteger(LuaState state, int argumentId)
		{
			BadArgument(state, argumentId, "number has no integer representation");
		}

		public static void ThrowBadArgumentIfNumberIsNotInteger(LuaState state, int argumentId, double value)
		{
			if (!MathEx.IsInteger(value))
			{
				BadArgumentNumberIsNotInteger(state, argumentId);
			}
		}

		private static string CreateMessage(Traceback traceback, LuaValue errorObject, int level)
		{
			PooledList<char> list = new PooledList<char>(64);
			list.Clear();
			try
			{
				list.AddRange("Lua-CSharp: ");
				traceback.WriteLastLuaTrace(ref list, level);
				list.AddRange($"{errorObject}");
				return list.AsSpan().ToString();
			}
			finally
			{
				list.Dispose();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		Traceback? ILuaTracebackBuildable.BuildOrGet()
		{
			if (luaTraceback != null)
			{
				return luaTraceback;
			}
			if (State != null)
			{
				Span<CallStackFrame> span = State.ExceptionTrace.AsSpan();
				if (span.IsEmpty)
				{
					return null;
				}
				luaTraceback = new Traceback(State, span);
				State.ExceptionTrace.Clear();
				State = null;
			}
			return luaTraceback;
		}

		internal void Forget()
		{
			State?.ExceptionTrace.Clear();
			State = null;
		}

		internal string MinimalMessage()
		{
			string text = base.InnerException?.ToString() ?? ErrorObject.ToString();
			if (level <= 0)
			{
				return text;
			}
			if (luaTraceback == null)
			{
				if (State != null)
				{
					Span<CallStackFrame> span = State.ExceptionTrace.AsSpan();
					level = Math.Min(level, span.Length + 1);
					int num = level - 1;
					span = span.Slice(0, span.Length - num);
					if (span.IsEmpty)
					{
						return ErrorObject.ToString();
					}
					PooledList<char> list = new PooledList<char>(64);
					list.Clear();
					try
					{
						Traceback.WriteLastLuaTrace(span, ref list);
						list.AddRange(text);
						return list.AsSpan().ToString();
					}
					finally
					{
						list.Dispose();
					}
				}
				return text;
			}
			PooledList<char> list2 = new PooledList<char>(64);
			list2.Clear();
			try
			{
				luaTraceback.WriteLastLuaTrace(ref list2, level);
				list2.AddRange(text);
				return list2.AsSpan().ToString();
			}
			finally
			{
				list2.Dispose();
			}
		}

		public override string ToString()
		{
			if (LuaTraceback == null)
			{
				return base.ToString();
			}
			PooledList<char> pooledList = new PooledList<char>(64);
			pooledList.Clear();
			try
			{
				pooledList.AddRange(Message);
				pooledList.Add('\n');
				pooledList.AddRange(LuaTraceback.ToString());
				pooledList.Add('\n');
				pooledList.AddRange(StackTrace);
				return pooledList.AsSpan().ToString();
			}
			finally
			{
				pooledList.Dispose();
			}
		}
	}
	public class LuaAssertionException : LuaRuntimeException
	{
		public LuaAssertionException(LuaState? traceback, string message)
			: base(traceback, message)
		{
		}
	}
	public class LuaModuleNotFoundException : Exception
	{
		public LuaModuleNotFoundException(string moduleName)
			: base("module '" + moduleName + "' not found")
		{
		}
	}
	public sealed class LuaCanceledException : OperationCanceledException, ILuaTracebackBuildable
	{
		private Traceback? luaTraceback;

		public Traceback? LuaTraceback
		{
			get
			{
				if (luaTraceback == null)
				{
					((ILuaTracebackBuildable)this).BuildOrGet();
				}
				return luaTraceback;
			}
		}

		internal LuaState? State { get; private set; }

		internal LuaCanceledException(LuaState state, CancellationToken cancellationToken, Exception? innerException = null)
			: base("The operation was cancelled during execution on Lua.", innerException, cancellationToken)
		{
			state.CurrentException?.BuildOrGet();
			state.ExceptionTrace.Clear();
			state.CurrentException = this;
			State = state;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		Traceback? ILuaTracebackBuildable.BuildOrGet()
		{
			if (luaTraceback != null)
			{
				return luaTraceback;
			}
			if (State != null)
			{
				Span<CallStackFrame> span = State.ExceptionTrace.AsSpan();
				if (span.IsEmpty)
				{
					return null;
				}
				luaTraceback = new Traceback(State, span);
				State.ExceptionTrace.Clear();
				State = null;
			}
			return luaTraceback;
		}
	}
	public interface ILuaModuleLoader
	{
		bool Exists(string moduleName);

		ValueTask<LuaModule> LoadAsync(string moduleName, CancellationToken cancellationToken = default(CancellationToken));
	}
	internal static class EnumerableEx
	{
		public static IEnumerable<IEnumerable<T>> GroupConsecutiveBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (keySelector == null)
			{
				throw new ArgumentNullException("keySelector");
			}
			using IEnumerator<T> enumerator = source.GetEnumerator();
			if (!enumerator.MoveNext())
			{
				yield break;
			}
			List<T> list = new List<T>(1) { enumerator.Current };
			TKey x = keySelector(enumerator.Current);
			while (enumerator.MoveNext())
			{
				TKey currentKey = keySelector(enumerator.Current);
				if (!EqualityComparer<TKey>.Default.Equals(x, currentKey))
				{
					yield return list;
					list = new List<T>();
				}
				list.Add(enumerator.Current);
				x = currentKey;
			}
			yield return list;
		}
	}
	internal static class FarmHash
	{
		private struct Pair
		{
			public ulong first;

			public ulong second;

			public Pair(ulong first, ulong second)
			{
				this.first = first;
				this.second = second;
			}
		}

		private const ulong k0 = 14097894508562428199uL;

		private const ulong k1 = 13011662864482103923uL;

		private const ulong k2 = 11160318154034397263uL;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static ulong Hash64(byte[] bytes, int offset, int count)
		{
			fixed (byte* s = &bytes[offset])
			{
				return Hash64(s, (uint)count);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static ulong Hash64(ReadOnlySpan<byte> bytes)
		{
			fixed (byte* reference = &MemoryMarshal.GetReference(bytes))
			{
				return Hash64(reference, (uint)bytes.Length);
			}
		}

		private unsafe static uint Fetch32(byte* p)
		{
			return *(uint*)p;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static Pair make_pair(ulong first, ulong second)
		{
			return new Pair(first, second);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static void swap(ref ulong x, ref ulong z)
		{
			ulong num = z;
			z = x;
			x = num;
		}

		private unsafe static ulong Fetch64(byte* p)
		{
			return *(ulong*)p;
		}

		private static ulong Rotate64(ulong val, int shift)
		{
			if (shift != 0)
			{
				return (val >> shift) | (val << 64 - shift);
			}
			return val;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static ulong ShiftMix(ulong val)
		{
			return val ^ (val >> 47);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static ulong HashLen16(ulong u, ulong v, ulong mul)
		{
			ulong num = (u ^ v) * mul;
			num ^= num >> 47;
			ulong num2 = (v ^ num) * mul;
			return (num2 ^ (num2 >> 47)) * mul;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong Hash64(byte* s, uint len)
		{
			if (len <= 16)
			{
				return HashLen0to16(s, len);
			}
			if (len <= 32)
			{
				return HashLen17to32(s, len);
			}
			if (len <= 64)
			{
				return HashLen33to64(s, len);
			}
			if (len <= 96)
			{
				return HashLen65to96(s, len);
			}
			if (len <= 256)
			{
				return Hash64NA(s, len);
			}
			return Hash64UO(s, len);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen0to16(byte* s, uint len)
		{
			switch (len)
			{
			default:
			{
				ulong num7 = (ulong)(-7286425919675154353L + len * 2);
				ulong num8 = Fetch64(s) + 11160318154034397263uL;
				ulong num9 = Fetch64(s + len - 8);
				ulong u = Rotate64(num9, 37) * num7 + num8;
				ulong v = (Rotate64(num8, 25) + num9) * num7;
				return HashLen16(u, v, num7);
			}
			case 4u:
			case 5u:
			case 6u:
			case 7u:
			{
				ulong mul = (ulong)(-7286425919675154353L + len * 2);
				ulong num6 = Fetch32(s);
				return HashLen16(len + (num6 << 3), Fetch32(s + len - 4), mul);
			}
			case 1u:
			case 2u:
			case 3u:
			{
				byte num = *s;
				ushort num2 = s[len >> 1];
				ushort num3 = s[len - 1];
				int num4 = num + (num2 << 8);
				uint num5 = len + (uint)(num3 << 2);
				return ShiftMix((ulong)(((uint)num4 * -7286425919675154353L) ^ (num5 * -4348849565147123417L))) * 11160318154034397263uL;
			}
			case 0u:
				return 11160318154034397263uL;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen17to32(byte* s, uint len)
		{
			ulong num = (ulong)(-7286425919675154353L + len * 2);
			ulong num2 = Fetch64(s) * 13011662864482103923uL;
			ulong num3 = Fetch64(s + 8);
			ulong num4 = Fetch64(s + len - 8) * num;
			ulong num5 = Fetch64(s + len - 16) * 11160318154034397263uL;
			return HashLen16(Rotate64(num2 + num3, 43) + Rotate64(num4, 30) + num5, num2 + Rotate64(num3 + 11160318154034397263uL, 18) + num4, num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong H32(byte* s, uint len, ulong mul, ulong seed0 = 0uL, ulong seed1 = 0uL)
		{
			ulong num = Fetch64(s) * 13011662864482103923uL;
			ulong num2 = Fetch64(s + 8);
			ulong num3 = Fetch64(s + len - 8) * mul;
			ulong num4 = Fetch64(s + len - 16) * 11160318154034397263uL;
			ulong num5 = Rotate64(num + num2, 43) + Rotate64(num3, 30) + num4 + seed0;
			ulong num6 = num + Rotate64(num2 + 11160318154034397263uL, 18) + num3 + seed1;
			num = ShiftMix((num5 ^ num6) * mul);
			return ShiftMix((num6 ^ num) * mul);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen33to64(byte* s, uint len)
		{
			ulong num = (ulong)(-7286425919675154383L + 2 * len);
			ulong num2 = H32(s, 32u, 11160318154034397233uL, 0uL, 0uL);
			return (H32(s + len - 32, 32u, num, 0uL, 0uL) * num + num2) * num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen65to96(byte* s, uint len)
		{
			ulong num = (ulong)(-7286425919675154467L + 2 * len);
			ulong num2 = H32(s, 32u, 11160318154034397149uL, 0uL, 0uL);
			ulong num3 = H32(s + 32, 32u, num, 0uL, 0uL);
			return (H32(s + len - 32, 32u, num, num2, num3) * 9 + (num2 >> 17) + (num3 >> 21)) * num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static Pair WeakHashLen32WithSeeds(ulong w, ulong x, ulong y, ulong z, ulong a, ulong b)
		{
			a += w;
			b = Rotate64(b + a + z, 21);
			ulong num = a;
			a += x;
			a += y;
			b += Rotate64(a, 44);
			return make_pair(a + z, b + num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static Pair WeakHashLen32WithSeeds(byte* s, ulong a, ulong b)
		{
			return WeakHashLen32WithSeeds(Fetch64(s), Fetch64(s + 8), Fetch64(s + 16), Fetch64(s + 24), a, b);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong Hash64NA(byte* s, uint len)
		{
			ulong num = 81uL;
			ulong num2 = 2480279821605975764uL;
			ulong x = ShiftMix((ulong)((long)num2 * -7286425919675154353L + 113)) * 11160318154034397263uL;
			Pair pair = make_pair(0uL, 0uL);
			Pair pair2 = make_pair(0uL, 0uL);
			num = (ulong)((long)num * -7286425919675154353L) + Fetch64(s);
			byte* ptr = s + (len - 1) / 64 * 64;
			byte* ptr2 = ptr + ((len - 1) & 0x3F) - 63;
			do
			{
				num = Rotate64(num + num2 + pair.first + Fetch64(s + 8), 37) * 13011662864482103923uL;
				num2 = Rotate64(num2 + pair.second + Fetch64(s + 48), 42) * 13011662864482103923uL;
				num ^= pair2.second;
				num2 += pair.first + Fetch64(s + 40);
				x = Rotate64(x + pair2.first, 33) * 13011662864482103923uL;
				pair = WeakHashLen32WithSeeds(s, pair.second * 13011662864482103923uL, num + pair2.first);
				pair2 = WeakHashLen32WithSeeds(s + 32, x + pair2.second, num2 + Fetch64(s + 16));
				swap(ref x, ref num);
				s += 64;
			}
			while (s != ptr);
			ulong num3 = 13011662864482103923uL + ((x & 0xFF) << 1);
			s = ptr2;
			pair2.first += (len - 1) & 0x3F;
			pair.first += pair2.first;
			pair2.first += pair.first;
			num = Rotate64(num + num2 + pair.first + Fetch64(s + 8), 37) * num3;
			num2 = Rotate64(num2 + pair.second + Fetch64(s + 48), 42) * num3;
			num ^= pair2.second * 9;
			num2 += pair.first * 9 + Fetch64(s + 40);
			x = Rotate64(x + pair2.first, 33) * num3;
			pair = WeakHashLen32WithSeeds(s, pair.second * num3, num + pair2.first);
			pair2 = WeakHashLen32WithSeeds(s + 32, x + pair2.second, num2 + Fetch64(s + 16));
			swap(ref x, ref num);
			return HashLen16((ulong)((long)HashLen16(pair.first, pair2.first, num3) + (long)ShiftMix(num2) * -4348849565147123417L) + x, HashLen16(pair.second, pair2.second, num3) + num, num3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static ulong H(ulong x, ulong y, ulong mul, int r)
		{
			ulong num = (x ^ y) * mul;
			num ^= num >> 47;
			return Rotate64((y ^ num) * mul, r) * mul;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong Hash64UO(byte* s, uint len)
		{
			ulong num = 81uL;
			ulong num2 = 113uL;
			ulong z = ShiftMix(num2 * 11160318154034397263uL) * 11160318154034397263uL;
			Pair pair = make_pair(81uL, 0uL);
			Pair pair2 = make_pair(0uL, 0uL);
			ulong x = num - z;
			num *= 11160318154034397263uL;
			ulong num3 = 11160318154034397263uL + (x & 0x82);
			byte* ptr = s + (len - 1) / 64 * 64;
			byte* ptr2 = ptr + ((len - 1) & 0x3F) - 63;
			do
			{
				ulong num4 = Fetch64(s);
				ulong num5 = Fetch64(s + 8);
				ulong num6 = Fetch64(s + 16);
				ulong num7 = Fetch64(s + 24);
				ulong num8 = Fetch64(s + 32);
				ulong num9 = Fetch64(s + 40);
				ulong num10 = Fetch64(s + 48);
				ulong num11 = Fetch64(s + 56);
				num += num4 + num5;
				num2 += num6;
				z += num7;
				pair.first += num8;
				pair.second += num9 + num5;
				pair2.first += num10;
				pair2.second += num11;
				num = Rotate64(num, 26);
				num *= 9;
				num2 = Rotate64(num2, 29);
				z *= num3;
				pair.first = Rotate64(pair.first, 33);
				pair.second = Rotate64(pair.second, 30);
				pair2.first ^= num;
				pair2.first *= 9uL;
				z = Rotate64(z, 32);
				z += pair2.second;
				pair2.second += z;
				z *= 9;
				swap(ref x, ref num2);
				z += num4 + num10;
				pair.first += num6;
				pair.second += num7;
				pair2.first += num8;
				pair2.second += num9 + num10;
				num += num5;
				num2 += num11;
				num2 += pair.first;
				pair.first += num - num2;
				pair.second += pair2.first;
				pair2.first += pair.second;
				pair2.second += num - num2;
				num += pair2.second;
				pair2.second = Rotate64(pair2.second, 34);
				swap(ref x, ref z);
				s += 64;
			}
			while (s != ptr);
			s = ptr2;
			x *= 9;
			pair.second = Rotate64(pair.second, 28);
			pair.first = Rotate64(pair.first, 20);
			pair2.first += (len - 1) & 0x3F;
			x += num2;
			num2 += x;
			num = Rotate64(num2 - num + pair.first + Fetch64(s + 8), 37) * num3;
			num2 = Rotate64(num2 ^ pair.second ^ Fetch64(s + 48), 42) * num3;
			num ^= pair2.second * 9;
			num2 += pair.first + Fetch64(s + 40);
			z = Rotate64(z + pair2.first, 33) * num3;
			pair = WeakHashLen32WithSeeds(s, pair.second * num3, num + pair2.first);
			pair2 = WeakHashLen32WithSeeds(s + 32, z + pair2.second, num2 + Fetch64(s + 16));
			return H(HashLen16(pair.first + num, pair2.first ^ num2, num3) + z - x, H(pair.second + num2, pair2.second + z, 11160318154034397263uL, 30) ^ num, 11160318154034397263uL, 31);
		}
	}
	internal sealed class LuaGlobalState
	{
		private readonly LuaState mainState;

		private FastStackCore<LuaState> stateStack;

		private readonly LuaTable environment;

		private readonly LuaTable registry = new LuaTable();

		private readonly UpValue envUpValue;

		private FastStackCore<LuaDebug.LuaDebugBuffer> debugBufferPool;

		private LuaTable? nilMetatable;

		private LuaTable? numberMetatable;

		private LuaTable? stringMetatable;

		private LuaTable? booleanMetatable;

		private LuaTable? functionMetatable;

		private LuaTable? stateMetatable;

		public LuaPlatform Platform { get; set; }

		public ILuaModuleLoader? ModuleLoader { get; set; }

		internal UpValue EnvUpValue => envUpValue;

		internal ref FastStackCore<LuaState> ThreadStack => ref stateStack;

		internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;

		public LuaTable Environment => environment;

		public LuaTable Registry => registry;

		public LuaTable LoadedModules => registry["_LOADED"].Read<LuaTable>();

		public LuaTable PreloadModules => registry["_PRELOAD"].Read<LuaTable>();

		public LuaState MainThread => mainState;

		public static LuaGlobalState Create(LuaPlatform? platform = null)
		{
			return new LuaGlobalState(platform ?? LuaPlatform.Default);
		}

		private LuaGlobalState(LuaPlatform platform)
		{
			mainState = new LuaState(this);
			environment = new LuaTable();
			envUpValue = UpValue.Closed(environment);
			registry["_LOADED"] = new LuaTable(0, 8);
			registry["_PRELOAD"] = new LuaTable(0, 8);
			Platform = platform;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryGetMetatable(LuaValue value, [NotNullWhen(true)] out LuaTable? result)
		{
			result = value.Type switch
			{
				LuaValueType.Nil => nilMetatable, 
				LuaValueType.Boolean => booleanMetatable, 
				LuaValueType.String => stringMetatable, 
				LuaValueType.Number => numberMetatable, 
				LuaValueType.Function => functionMetatable, 
				LuaValueType.Thread => stateMetatable, 
				LuaValueType.UserData => value.UnsafeRead<ILuaUserData>().Metatable, 
				LuaValueType.Table => value.UnsafeRead<LuaTable>().Metatable, 
				_ => null, 
			};
			return result != null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void SetMetatable(LuaValue value, LuaTable metatable)
		{
			switch (value.Type)
			{
			case LuaValueType.Nil:
				nilMetatable = metatable;
				break;
			case LuaValueType.Boolean:
				booleanMetatable = metatable;
				break;
			case LuaValueType.String:
				stringMetatable = metatable;
				break;
			case LuaValueType.Number:
				numberMetatable = metatable;
				break;
			case LuaValueType.Function:
				functionMetatable = metatable;
				break;
			case LuaValueType.Thread:
				stateMetatable = metatable;
				break;
			case LuaValueType.UserData:
				value.UnsafeRead<ILuaUserData>().Metatable = metatable;
				break;
			case LuaValueType.Table:
				value.UnsafeRead<LuaTable>().Metatable = metatable;
				break;
			case LuaValueType.LightUserData:
				break;
			}
		}
	}
	internal static class MathEx
	{
		private const ulong PositiveInfinityBits = 9218868437227405312uL;

		public const int ArrayMexLength = 2147483591;

		private const long DBL_EXP_MASK = 9218868437227405312L;

		private const int DBL_MANT_BITS = 52;

		private const long DBL_SGN_MASK = long.MinValue;

		private const long DBL_MANT_MASK = 4503599627370495L;

		private const long DBL_EXP_CLR_MASK = -9218868437227405313L;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsInteger(double d)
		{
			if (IsFinite(d))
			{
				return d == Math.Truncate(d);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsFinite(double d)
		{
			return (~BitCast<double, ulong>(d) & 0x7FF0000000000000L) != 0;
		}

		private static TTo BitCast<TFrom, TTo>(TFrom source)
		{
			return Unsafe.ReadUnaligned<TTo>(in Unsafe.As<TFrom, byte>(ref source));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int NewArrayCapacity(int size)
		{
			int num = size * 2;
			if ((uint)num > 2147483591u)
			{
				num = 2147483591;
			}
			return num;
		}

		public static (double m, int e) Frexp(double d)
		{
			long num = BitConverter.DoubleToInt64Bits(d);
			int num2 = (int)((num & 0x7FF0000000000000L) >> 52);
			int item = 0;
			if (num2 == 2047 || d == 0.0)
			{
				d += d;
			}
			else
			{
				item = num2 - 1022;
				if (num2 == 0)
				{
					d *= BitConverter.Int64BitsToDouble(4850376798678024192L);
					num = BitConverter.DoubleToInt64Bits(d);
					num2 = (int)((num & 0x7FF0000000000000L) >> 52);
					item = num2 - 1022 - 54;
				}
				d = BitConverter.Int64BitsToDouble((num & -9218868437227405313L) | 0x3FE0000000000000L);
			}
			return (m: d, e: item);
		}

		public static (int i, double f) Modf(double d)
		{
			return (i: (int)Math.Truncate(d), f: d % 1.0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int NextPowerOfTwo(int x)
		{
			if (x <= 0)
			{
				return 0;
			}
			x--;
			x |= x >> 1;
			x |= x >> 2;
			x |= x >> 4;
			x |= x >> 8;
			x |= x >> 16;
			return x + 1;
		}
	}
	public class LuaFunction(string name, Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func)
	{
		public string Name { get; } = name;

		internal Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> Func { get; } = func;

		public LuaFunction(Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func)
			: this("anonymous", func)
		{
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly record struct LuaFunctionExecutionContext
	{
		internal LuaGlobalState GlobalState => State.GlobalState;

		public LuaState State { get; init; }

		public required int ArgumentCount { get; init; }

		public required int ReturnFrameBase { get; init; }

		public int FrameBase => State.Stack.Count - ArgumentCount;

		public ReadOnlySpan<LuaValue> Arguments
		{
			get
			{
				Span<LuaValue> span = State.Stack.AsSpan();
				int argumentCount = ArgumentCount;
				return span.Slice(span.Length - argumentCount);
			}
		}

		public ReadOnlyMemory<LuaValue> ArgumentsMemory
		{
			get
			{
				LuaStack stack = State.Stack;
				Memory<LuaValue> bufferMemory = stack.GetBufferMemory();
				int num = stack.Count - ArgumentCount;
				return bufferMemory.Slice(num, stack.Count - num);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool HasArgument(int index)
		{
			if (ArgumentCount > index)
			{
				return Arguments[index].Type != LuaValueType.Nil;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public LuaValue GetArgument(int index)
		{
			ThrowIfArgumentNotExists(index);
			return Arguments[index];
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal LuaValue GetArgumentOrDefault(int index, LuaValue defaultValue = default(LuaValue))
		{
			if (ArgumentCount <= index)
			{
				return defaultValue;
			}
			return Arguments[index];
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T GetArgument<T>(int index)
		{
			ThrowIfArgumentNotExists(index);
			LuaValue luaValue = Arguments[index];
			if (!luaValue.TryRead<T>(out var result))
			{
				Type typeFromHandle = typeof(T);
				LuaValueType result3;
				if ((typeFromHandle == typeof(int) || typeFromHandle == typeof(long)) && luaValue.TryReadNumber(out var _))
				{
					LuaRuntimeException.BadArgumentNumberIsNotInteger(State, index + 1);
				}
				else if (LuaValue.TryGetLuaValueType(typeFromHandle, out result3))
				{
					LuaRuntimeException.BadArgument(State, index + 1, result3, luaValue.Type);
				}
				else
				{
					LuaValueType type = luaValue.Type;
					if (type - 6 <= LuaValueType.Boolean)
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.UnsafeRead<object>()?.GetType().ToString() ?? "userdata: 0");
					}
					else
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.TypeToString());
					}
				}
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal T GetArgumentOrDefault<T>(int index, T defaultValue = default(T))
		{
			if (ArgumentCount <= index)
			{
				return defaultValue;
			}
			LuaValue luaValue = Arguments[index];
			if (luaValue.Type == LuaValueType.Nil)
			{
				return defaultValue;
			}
			if (!luaValue.TryRead<T>(out var result))
			{
				Type typeFromHandle = typeof(T);
				LuaValueType result3;
				if ((typeFromHandle == typeof(int) || typeFromHandle == typeof(long)) && luaValue.TryReadNumber(out var _))
				{
					LuaRuntimeException.BadArgumentNumberIsNotInteger(State, index + 1);
				}
				else if (LuaValue.TryGetLuaValueType(typeFromHandle, out result3))
				{
					LuaRuntimeException.BadArgument(State, index + 1, result3, luaValue.Type);
				}
				else
				{
					LuaValueType type = luaValue.Type;
					if (type - 6 <= LuaValueType.Boolean)
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.UnsafeRead<object>()?.GetType().ToString() ?? "userdata: 0");
					}
					else
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.TypeToString());
					}
				}
			}
			return result;
		}

		public int Return()
		{
			State.Stack.PopUntil(ReturnFrameBase);
			return 0;
		}

		public int Return(LuaValue result)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + 1);
			stack.FastGet(ReturnFrameBase) = result;
			return 1;
		}

		public int Return(LuaValue result0, LuaValue result1)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + 2);
			stack.FastGet(ReturnFrameBase) = result0;
			stack.FastGet(ReturnFrameBase + 1) = result1;
			return 2;
		}

		public int Return(LuaValue result0, LuaValue result1, LuaValue result2)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + 3);
			stack.FastGet(ReturnFrameBase) = result0;
			stack.FastGet(ReturnFrameBase + 1) = result1;
			stack.FastGet(ReturnFrameBase + 2) = result2;
			return 3;
		}

		public int Return(ReadOnlySpan<LuaValue> results)
		{
			LuaStack stack = State.Stack;
			stack.EnsureCapacity(ReturnFrameBase + results.Length);
			Span<LuaValue> buffer = stack.GetBuffer();
			int returnFrameBase = ReturnFrameBase;
			results.CopyTo(buffer.Slice(returnFrameBase, ReturnFrameBase + results.Length - returnFrameBase));
			stack.SetTop(ReturnFrameBase + results.Length);
			return results.Length;
		}

		internal int Return(LuaValue result0, ReadOnlySpan<LuaValue> results)
		{
			LuaStack stack = State.Stack;
			stack.EnsureCapacity(ReturnFrameBase + results.Length);
			stack.SetTop(ReturnFrameBase + results.Length + 1);
			Span<LuaValue> buffer = stack.GetBuffer();
			buffer[ReturnFrameBase] = result0;
			int num = ReturnFrameBase + 1;
			results.CopyTo(buffer.Slice(num, ReturnFrameBase + results.Length + 1 - num));
			return results.Length + 1;
		}

		public Span<LuaValue> GetReturnBuffer(int count)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + count);
			Span<LuaValue> buffer = stack.GetBuffer();
			int returnFrameBase = ReturnFrameBase;
			return buffer.Slice(returnFrameBase, ReturnFrameBase + count - returnFrameBase);
		}

		public CSharpClosure? GetCsClosure()
		{
			return State.GetCurrentFrame().Function as CSharpClosure;
		}

		internal void ThrowBadArgument(int index, string message)
		{
			LuaRuntimeException.BadArgument(State, index, State.GetCurrentFrame().Function.Name, message);
		}

		private void ThrowIfArgumentNotExists(int index)
		{
			if (ArgumentCount <= index)
			{
				LuaRuntimeException.BadArgument(State, index + 1);
			}
		}

		[CompilerGenerated]
		private bool PrintMembers(StringBuilder builder)
		{
			builder.Append("State = ");
			builder.Append(State);
			builder.Append(", ArgumentCount = ");
			builder.Append(ArgumentCount.ToString());
			builder.Append(", ReturnFrameBase = ");
			builder.Append(ReturnFrameBase.ToString());
			builder.Append(", FrameBase = ");
			builder.Append(FrameBase.ToString());
			builder.Append(", Arguments = ");
			builder.Append(Arguments.ToString());
			builder.Append(", ArgumentsMemory = ");
			builder.Append(ArgumentsMemory.ToString());
			return true;
		}
	}
	public enum LuaModuleType
	{
		Text,
		Bytes
	}
	public readonly struct LuaModule
	{
		private readonly string name;

		private readonly LuaModuleType type;

		private readonly ReadOnlyMemory<char> text;

		private readonly ReadOnlyMemory<byte> bytes;

		public string Name => name;

		public LuaModuleType Type => type;

		public LuaModule(string name, ReadOnlyMemory<char> text)
		{
			bytes = default(ReadOnlyMemory<byte>);
			this.name = name;
			type = LuaModuleType.Text;
			this.text = text;
		}

		public LuaModule(string name, ReadOnlyMemory<byte> bytes)
		{
			text = default(ReadOnlyMemory<char>);
			this.name = name;
			type = LuaModuleType.Bytes;
			this.bytes = bytes;
		}

		public LuaModule(string name, string text)
			: this(name, text.AsMemory())
		{
		}

		public LuaModule(string name, byte[] bytes)
			: this(name, new ReadOnlyMemory<byte>(bytes))
		{
		}

		public ReadOnlySpan<char> ReadText()
		{
			if (type != LuaModuleType.Text)
			{
				throw new Exception();
			}
			return text.Span;
		}

		public ReadOnlySpan<byte> ReadBytes()
		{
			if (type != LuaModuleType.Bytes)
			{
				throw new Exception();
			}
			return bytes.Span;
		}
	}
	public readonly struct LuaStackReader : IDisposable
	{
		private readonly LuaStack stack;

		private readonly int returnBase;

		public int Count => stack.Count - returnBase;

		public int Length => stack.Count - returnBase;

		public LuaValue this[int index] => AsSpan()[index];

		internal LuaStackReader(LuaStack stack, int returnBase)
		{
			this.stack = stack;
			this.returnBase = returnBase;
		}

		public ReadOnlySpan<LuaValue> AsSpan()
		{
			return stack.AsSpan().Slice(returnBase);
		}

		public void Dispose()
		{
			stack.PopUntil(returnBase);
		}
	}
	public class LuaState : IDisposable
	{
		private class ThreadCoreData : IPoolNode<ThreadCoreData>
		{
			internal readonly LuaStack Stack = new LuaStack();

			internal FastStackCore<CallStackFrame> CallStack;

			private static LinkedPool<ThreadCoreData> pool;

			private ThreadCoreData? nextNode;

			public ref ThreadCoreData? NextNode => ref nextNode;

			private void Clear()
			{
				Stack.Clear();
				CallStack.Clear();
			}

			public static ThreadCoreData Create()
			{
				if (!pool.TryPop(out ThreadCoreData result))
				{
					return new ThreadCoreData();
				}
				return result;
			}

			public void Release()
			{
				Clear();
				pool.TryPush(this);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <RunAsync>d__87 : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<int> <>t__builder;

			public LuaFunction function;

			public LuaState <>4__this;

			public CancellationToken cancellationToken;

			public int argumentCount;

			public int returnBase;

			private int <callStackTop>5__2;

			private ValueTaskAwaiter<int> <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				LuaState luaState = <>4__this;
				int result;
				try
				{
					LuaFunctionExecutionContext luaFunctionExecutionContext = default(LuaFunctionExecutionContext);
					if ((uint)num > 1u)
					{
						if (function == null)
						{
							throw new ArgumentNullException("function");
						}
						luaState.ThrowIfCancellationRequested(cancellationToken);
						LuaState luaState2 = luaState;
						int num2 = function.GetVariableArgumentCount(argumentCount);
						if (num2 != 0)
						{
							if (num2 < 0)
							{
								luaState2.Stack.SetTop(luaState2.Stack.Count - num2);
								num2 = 0;
							}
							else
							{
								LuaVirtualMachine.PrepareVariableArgument(luaState2.Stack, argumentCount, num2);
							}
							argumentCount -= num2;
						}
						CallStackFrame frame = new CallStackFrame
						{
							Base = luaState2.Stack.Count - argumentCount,
							VariableArgumentCount = num2,
							Function = function,
							ReturnBase = returnBase
						};
						if (luaState2.IsInHook)
						{
							frame.Flags |= CallStackFrameFlags.InHook;
						}
						luaState2.PushCallStackFrame(in frame);
						luaFunctionExecutionContext = new LuaFunctionExecutionContext
						{
							State = luaState2,
							ArgumentCount = argumentCount,
							ReturnFrameBase = returnBase
						};
						<callStackTop>5__2 = luaState2.CallStackFrameCount;
					}
					try
					{
						ValueTaskAwaiter<int> awaiter;
						if (num == 0)
						{
							awaiter = <>u__1;
							<>u__1 = default(ValueTaskAwaiter<int>);
							num = (<>1__state = -1);
							goto IL_01b3;
						}
						if (num != 1)
						{
							if (luaState.CallOrReturnHookMask.Value != 0 && !luaState.IsInHook)
							{
								awaiter = LuaVirtualMachine.ExecuteCallHook(luaFunctionExecutionContext, cancellationToken).GetAwaiter();
								if (!awaiter.IsCompleted)
								{
									num = (<>1__state = 0);
									<>u__1 = awaiter;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
									return;
								}
								goto IL_01b3;
							}
							awaiter = function.Func(luaFunctionExecutionContext, cancellationToken).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 1);
								<>u__1 = awaiter;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
								return;
							}
						}
						else
						{
							awaiter = <>u__1;
							<>u__1 = default(ValueTaskAwaiter<int>);
							num = (<>1__state = -1);
						}
						result = awaiter.GetResult();
						goto end_IL_0131;
						IL_01b3:
						result = awaiter.GetResult();
						end_IL_0131:;
					}
					finally
					{
						if (num < 0)
						{
							luaState.PopCallStackFrameUntil(<callStackTop>5__2 - 1);
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(result);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		private FastListCore<UpValue> openUpValues;

		internal int CallCount;

		private ThreadCoreData? CoreData;

		private CoroutineCore? coroutine;

		internal bool IsLineHookEnabled;

		internal BitFlags2 CallOrReturnHookMask;

		internal bool IsInHook;

		internal long HookCount;

		internal int BaseHookCount;

		internal int LastPc;

		internal ILuaTracebackBuildable? CurrentException;

		internal readonly ReversedStack<CallStackFrame> ExceptionTrace = new ReversedStack<CallStackFrame>();

		internal LuaFunction? LastCallerFunction;

		internal LuaGlobalState GlobalState { get; }

		internal ref FastListCore<UpValue> OpenUpValues => ref openUpValues;

		public bool IsRunning => CallStackFrameCount != 0;

		public bool IsCoroutine => coroutine != null;

		internal LuaFunction? Hook { get; set; }

		public LuaFunction? CoroutineFunction => coroutine?.Function;

		public bool CanResume => GetStatus() == LuaThreadStatus.Suspended;

		public LuaStack Stack => CoreData.Stack;

		internal Traceback? LuaTraceback => coroutine?.Traceback;

		public LuaTable Environment => GlobalState.Environment;

		public LuaTable Registry => GlobalState.Registry;

		public LuaTable LoadedModules => GlobalState.LoadedModules;

		public LuaTable PreloadModules => GlobalState.PreloadModules;

		public LuaState MainThread => GlobalState.MainThread;

		public ILuaModuleLoader? ModuleLoader
		{
			get
			{
				return GlobalState.ModuleLoader;
			}
			set
			{
				GlobalState.ModuleLoader = value;
			}
		}

		public LuaPlatform Platform
		{
			get
			{
				return GlobalState.Platform;
			}
			set
			{
				GlobalState.Platform = value;
			}
		}

		internal bool IsCallHookEnabled
		{
			get
			{
				return CallOrReturnHookMask.Flag0;
			}
			set
			{
				CallOrReturnHookMask.Flag0 = value;
			}
		}

		internal bool IsReturnHookEnabled
		{
			get
			{
				return CallOrReturnHookMask.Flag1;
			}
			set
			{
				CallOrReturnHookMask.Flag1 = value;
			}
		}

		public int CallStackFrameCount
		{
			get
			{
				if (CoreData != null)
				{
					return CoreData.CallStack.Count;
				}
				return 0;
			}
		}

		internal LuaState(LuaGlobalState globalState)
		{
			GlobalState = globalState;
			CoreData = ThreadCoreData.Create();
		}

		internal LuaState(LuaGlobalState globalState, LuaFunction function, bool isProtectedMode)
		{
			GlobalState = globalState;
			CoreData = ThreadCoreData.Create();
			coroutine = new CoroutineCore(this, function, isProtectedMode);
		}

		public static LuaState Create()
		{
			return LuaGlobalState.Create().MainThread;
		}

		public static LuaState Create(LuaPlatform platform)
		{
			return LuaGlobalState.Create(platform).MainThread;
		}

		internal static LuaState CreateCoroutine(LuaGlobalState globalState, LuaFunction function, bool isProtectedMode = false)
		{
			return new LuaState(globalState, function, isProtectedMode);
		}

		public LuaState CreateThread()
		{
			return new LuaState(GlobalState);
		}

		public LuaState CreateCoroutine(LuaFunction function, bool isProtectedMode = false)
		{
			return new LuaState(GlobalState, function, isProtectedMode);
		}

		public LuaThreadStatus GetStatus()
		{
			if (coroutine != null)
			{
				return (LuaThreadStatus)coroutine.status;
			}
			return LuaThreadStatus.Running;
		}

		public void UnsafeSetStatus(LuaThreadStatus status)
		{
			if (coroutine != null)
			{
				coroutine.status = (byte)status;
			}
		}

		public ValueTask<int> ResumeAsync(LuaFunctionExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.ResumeAsyncCore(context.State.Stack, context.ArgumentCount, context.ReturnFrameBase, context.State, cancellationToken);
			}
			return new ValueTask<int>(context.Return(false, "cannot resume non-suspended coroutine"));
		}

		public ValueTask<int> ResumeAsync(LuaStack stack, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.ResumeAsyncCore(stack, stack.Count, 0, null, cancellationToken);
			}
			stack.Push(false);
			stack.Push("cannot resume non-suspended coroutine");
			return new ValueTask<int>(2);
		}

		public ValueTask<int> YieldAsync(LuaFunctionExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.YieldAsyncCore(context.State.Stack, context.ArgumentCount, context.ReturnFrameBase, context.State, cancellationToken);
			}
			throw new LuaRuntimeException(context.State, "attempt to yield from outside a coroutine");
		}

		public ValueTask<int> YieldAsync(LuaStack stack, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.YieldAsyncCore(stack, stack.Count, 0, null, cancellationToken);
			}
			throw new LuaRuntimeException(null, "attempt to yield from outside a coroutine");
		}

		public ref readonly CallStackFrame GetCurrentFrame()
		{
			return ref CoreData.CallStack.PeekRef();
		}

		public ReadOnlySpan<LuaValue> GetStackValues()
		{
			return (CoreData == null) ? default(Span<LuaValue>) : CoreData.Stack.AsSpan();
		}

		public ReadOnlySpan<CallStackFrame> GetCallStackFrames()
		{
			return (CoreData == null) ? default(Span<CallStackFrame>) : CoreData.CallStack.AsSpan();
		}

		internal CallStackFrame CreateCallStackFrame(LuaFunction function, int argumentCount, int returnBase, int callerInstructionIndex)
		{
			int num = function.GetVariableArgumentCount(argumentCount);
			if (num != 0)
			{
				if (num < 0)
				{
					Stack.SetTop(Stack.Count - num);
					argumentCount -= num;
					num = 0;
				}
				else
				{
					LuaVirtualMachine.PrepareVariableArgument(Stack, argumentCount, num);
				}
			}
			CallStackFrame result = new CallStackFrame
			{
				Base = Stack.Count - argumentCount,
				VariableArgumentCount = num,
				Function = function,
				ReturnBase = returnBase,
				CallerInstructionIndex = callerInstructionIndex
			};
			if (IsInHook)
			{
				result.Flags |= CallStackFrameFlags.InHook;
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PushCallStackFrame(in CallStackFrame frame)
		{
			CurrentException?.BuildOrGet();
			CurrentException = null;
			CoreData.CallStack.Push(in frame);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrameWithStackPop()
		{
			ThreadCoreData? coreData = CoreData;
			CallStackFrame element = coreData.CallStack.Pop();
			if (CurrentException != null)
			{
				ExceptionTrace.Push(element);
			}
			coreData.Stack.PopUntil(element.ReturnBase);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrameWithStackPop(int frameBase)
		{
			ThreadCoreData? coreData = CoreData;
			CallStackFrame element = coreData.CallStack.Pop();
			if (CurrentException != null)
			{
				ExceptionTrace.Push(element);
			}
			coreData.Stack.PopUntil(frameBase);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrame()
		{
			CallStackFrame element = CoreData.CallStack.Pop();
			if (CurrentException != null)
			{
				ExceptionTrace.Push(element);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrameUntil(int top)
		{
			ref FastStackCore<CallStackFrame> callStack = ref CoreData.CallStack;
			if (CurrentException != null)
			{
				ExceptionTrace.Push(callStack.AsSpan().Slice(top));
			}
			callStack.PopUntil(top);
		}

		public LuaTable GetCurrentEnvironment()
		{
			ReadOnlySpan<CallStackFrame> callStackFrames = GetCallStackFrames();
			for (int num = callStackFrames.Length - 1; num >= 0; num--)
			{
				if (callStackFrames[num].Function is LuaClosure luaClosure && luaClosure.Proto.UpValues.Length != 0 && !(luaClosure.Proto.UpValues[0].Name != "_ENV"))
				{
					return luaClosure.UpValues[0].GetValue().Read<LuaTable>();
				}
			}
			return Environment;
		}

		public void SetHook(LuaFunction? hook, string mask, int count = 0)
		{
			if (hook == null)
			{
				HookCount = 0L;
				BaseHookCount = 0;
				Hook = null;
				IsLineHookEnabled = false;
				IsCallHookEnabled = false;
				IsReturnHookEnabled = false;
				return;
			}
			HookCount = ((count > 0) ? (count + 1) : 0);
			BaseHookCount = count;
			IsLineHookEnabled = mask.Contains('l');
			IsCallHookEnabled = mask.Contains('c');
			IsReturnHookEnabled = mask.Contains('r');
			if (IsLineHookEnabled)
			{
				LastPc = ((CallStackFrameCount > 0) ? GetCurrentFrame().CallerInstructionIndex : (-1));
			}
			Hook = hook;
		}

		internal void DumpStackValues()
		{
			ReadOnlySpan<LuaValue> stackValues = GetStackValues();
			for (int i = 0; i < stackValues.Length; i++)
			{
				Console.WriteLine($"LuaStack [{i}]\t{stackValues[i]}");
			}
		}

		public Traceback GetTraceback()
		{
			return new Traceback(this, GetCallStackFrames());
		}

		public ValueTask<int> RunAsync(LuaFunction function, CancellationToken cancellationToken = default(CancellationToken))
		{
			return RunAsync(function, 0, Stack.Count, cancellationToken);
		}

		public ValueTask<int> RunAsync(LuaFunction function, int argumentCount, CancellationToken cancellationToken = default(CancellationToken))
		{
			return RunAsync(function, argumentCount, Stack.Count - argumentCount, cancellationToken);
		}

		[AsyncStateMachine(typeof(<RunAsync>d__87))]
		[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
		public ValueTask<int> RunAsync(LuaFunction function, int argumentCount, int returnBase, CancellationToken cancellationToken = default(CancellationToken))
		{
			<RunAsync>d__87 stateMachine = default(<RunAsync>d__87);
			stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<int>.Create();
			stateMachine.<>4__this = this;
			stateMachine.function = function;
			stateMachine.argumentCount = argumentCount;
			stateMachine.returnBase = returnBase;
			stateMachine.cancellationToken = cancellationToken;
			stateMachine.<>1__state = -1;
			stateMachine.<>t__builder.Start(ref stateMachine);
			return stateMachine.<>t__builder.Task;
		}

		public unsafe LuaClosure Load(ReadOnlySpan<char> chunk, string chunkName, LuaTable? environment = null)
		{
			Prototype proto;
			fixed (char* ptr = chunk)
			{
				proto = Lua.CodeAnalysis.Compilation.Parser.Parse(this, new Lua.CodeAnalysis.Compilation.TextReader(ptr, chunk.Length), chunkName);
			}
			return new LuaClosure(this, proto, environment);
		}

		public LuaClosure Load(ReadOnlySpan<byte> chunk, string? chunkName = null, string mode = "bt", LuaTable? environment = null)
		{
			if (chunk.Length > 4 && chunk[0] == 27)
			{
				if (!AllowsMode(mode, 'b'))
				{
					throw new Exception("attempt to load a binary chunk (mode is 't')");
				}
				return new LuaClosure(this, Lua.CodeAnalysis.Compilation.Parser.Undump(chunk, chunkName), environment);
			}
			if (!AllowsMode(mode, 't'))
			{
				throw new Exception("attempt to load a text chunk (mode is 'b')");
			}
			chunk = BomUtility.GetEncodingFromBytes(chunk, out Encoding encoding);
			int charCount = encoding.GetCharCount(chunk);
			char[] array = ArrayPool<char>.Shared.Rent(charCount);
			try
			{
				Span<char> span = array.AsSpan(0, charCount);
				encoding.GetChars(chunk, span);
				if (chunkName == null)
				{
					chunkName = span.ToString();
				}
				return Load(span, chunkName, environment);
			}
			finally
			{
				ArrayPool<char>.Shared.Return(array);
			}
			static bool AllowsMode(string text, char chunkMode)
			{
				return text.IndexOf(chunkMode) >= 0;
			}
		}

		internal UpValue GetOrAddUpValue(int registerIndex)
		{
			Span<UpValue> span = openUpValues.AsSpan();
			for (int i = 0; i < span.Length; i++)
			{
				UpValue upValue = span[i];
				if (upValue.RegisterIndex == registerIndex)
				{
					return upValue;
				}
			}
			UpValue upValue2 = UpValue.Open(this, registerIndex);
			openUpValues.Add(upValue2);
			return upValue2;
		}

		internal void CloseUpValues(int frameBase)
		{
			for (int i = 0; i < openUpValues.Length; i++)
			{
				UpValue upValue = openUpValues[i];
				if (upValue.RegisterIndex >= frameBase)
				{
					upValue.Close();
					openUpValues.RemoveAtSwapBack(i);
					i--;
				}
			}
		}

		public void Dispose()
		{
			if (CoreData != null)
			{
				if (CoreData.CallStack.Count != 0)
				{
					throw new InvalidOperationException("This state is running! Call stack is not empty!!");
				}
				CoreData.Release();
				CoreData = null;
			}
		}
	}
	public static class LuaStateExtensions
	{
		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <<CallAsync>g__Impl|31_0>d : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<LuaValue[]> <>t__builder;

			public LuaState state;

			public int funcIndex;

			public CancellationToken cancellationToken;

			private ValueTaskAwaiter<int> <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				LuaValue[] result;
				try
				{
					ValueTaskAwaiter<int> awaiter;
					if (num != 0)
					{
						awaiter = LuaVirtualMachine.Call(state, funcIndex, funcIndex, cancellationToken).GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = awaiter;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
							return;
						}
					}
					else
					{
						awaiter = <>u__1;
						<>u__1 = default(ValueTaskAwaiter<int>);
						num = (<>1__state = -1);
					}
					awaiter.GetResult();
					int argumentCount = state.Stack.Count - funcIndex;
					LuaStackReader luaStackReader = state.ReadStack(argumentCount);
					try
					{
						result = luaStackReader.AsSpan().ToArray();
					}
					finally
					{
						if (num < 0)
						{
							((IDisposable)luaStackReader/*cast due to .constrained prefix*/).Dispose();
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(result);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <DoFileAsync>d__5 : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<int> <>t__builder;

			public LuaState state;

			public string path;

			public CancellationToken cancellationToken;

			public Memory<LuaValue> buffer;

			private ValueTaskAwaiter<LuaClosure> <>u__1;

			private ValueTaskAwaiter<int> <>u__2;

			private void MoveNext()
			{
				int num = <>1__state;
				int count;
				try
				{
					ValueTaskAwaiter<int> awaiter;
					ValueTaskAwaiter<LuaClosure> awaiter2;
					if (num != 0)
					{
						if (num == 1)
						{
							awaiter = <>u__2;
							<>u__2 = default(ValueTaskAwaiter<int>);
							num = (<>1__state = -1);
							goto IL_00f3;
						}
						awaiter2 = state.LoadFileAsync(path, "bt", null, cancellationToken).GetAwaiter();
						if (!awaiter2.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = awaiter2;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref this);
							return;
						}
					}
					else
					{
						awaiter2 = <>u__1;
						<>u__1 = default(ValueTaskAwaiter<LuaClosure>);
						num = (<>1__state = -1);
					}
					LuaClosure result = awaiter2.GetResult();
					awaiter = state.RunAsync(result, 0, cancellationToken).GetAwaiter();
					if (!awaiter.IsCompleted)
					{
						num = (<>1__state = 1);
						<>u__2 = awaiter;
						<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
						return;
					}
					goto IL_00f3;
					IL_00f3:
					int result2 = awaiter.GetResult();
					LuaStackReader luaStackReader = state.ReadStack(result2);
					try
					{
						luaStackReader.AsSpan().Slice(0, Math.Min(buffer.Length, luaStackReader.Length)).CopyTo(buffer.Span);
						count = luaStackReader.Count;
					}
					finally
					{
						if (num < 0)
						{
							((IDisposable)luaStackReader/*cast due to .constrained prefix*/).Dispose();
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(count);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <DoFileAsync>d__6 : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<LuaValue[]> <>t__builder;

			public LuaState state;

			public string path;

			public CancellationToken cancellationToken;

			private ValueTaskAwaiter<LuaClosure> <>u__1;

			private ValueTaskAwaiter<int> <>u__2;

			private void MoveNext()
			{
				int num = <>1__state;
				LuaValue[] result3;
				try
				{
					ValueTaskAwaiter<int> awaiter;
					ValueTaskAwaiter<LuaClosure> awaiter2;
					if (num != 0)
					{
						if (num == 1)
						{
							awaiter = <>u__2;
							<>u__2 = default(ValueTaskAwaiter<int>);
							num = (<>1__state = -1);
							goto IL_00f3;
						}
						awaiter2 = state.LoadFileAsync(path, "bt", null, cancellationToken).GetAwaiter();
						if (!awaiter2.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = awaiter2;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref this);
							return;
						}
					}
					else
					{
						awaiter2 = <>u__1;
						<>u__1 = default(ValueTaskAwaiter<LuaClosure>);
						num = (<>1__state = -1);
					}
					LuaClosure result = awaiter2.GetResult();
					awaiter = state.RunAsync(result, 0, cancellationToken).GetAwaiter();
					if (!awaiter.IsCompleted)
					{
						num = (<>1__state = 1);
						<>u__2 = awaiter;
						<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
						return;
					}
					goto IL_00f3;
					IL_00f3:
					int result2 = awaiter.GetResult();
					LuaStackReader luaStackReader = state.ReadStack(result2);
					try
					{
						result3 = luaStackReader.AsSpan().ToArray();
					}
					finally
					{
						if (num < 0)
						{
							((IDisposable)luaStackReader/*cast due to .constrained prefix*/).Dispose();
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(result3);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <ExecuteAsync>d__7 : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<int> <>t__builder;

			public LuaState state;

			public LuaClosure closure;

			public CancellationToken cancellationToken;

			public Memory<LuaValue> buffer;

			private ValueTaskAwaiter<int> <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				int count;
				try
				{
					ValueTaskAwaiter<int> awaiter;
					if (num != 0)
					{
						awaiter = state.RunAsync(closure, 0, cancellationToken).GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = awaiter;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
							return;
						}
					}
					else
					{
						awaiter = <>u__1;
						<>u__1 = default(ValueTaskAwaiter<int>);
						num = (<>1__state = -1);
					}
					int result = awaiter.GetResult();
					LuaStackReader luaStackReader = state.ReadStack(result);
					try
					{
						luaStackReader.AsSpan().Slice(0, Math.Min(buffer.Length, luaStackReader.Length)).CopyTo(buffer.Span);
						count = luaStackReader.Count;
					}
					finally
					{
						if (num < 0)
						{
							((IDisposable)luaStackReader/*cast due to .constrained prefix*/).Dispose();
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(count);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <ExecuteAsync>d__8 : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<LuaValue[]> <>t__builder;

			public LuaState state;

			public LuaClosure closure;

			public CancellationToken cancellationToken;

			private ValueTaskAwaiter<int> <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				LuaValue[] result2;
				try
				{
					ValueTaskAwaiter<int> awaiter;
					if (num != 0)
					{
						awaiter = state.RunAsync(closure, 0, cancellationToken).GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = awaiter;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
							return;
						}
					}
					else
					{
						awaiter = <>u__1;
						<>u__1 = default(ValueTaskAwaiter<int>);
						num = (<>1__state = -1);
					}
					int result = awaiter.GetResult();
					LuaStackReader luaStackReader = state.ReadStack(result);
					try
					{
						result2 = luaStackReader.AsSpan().ToArray();
					}
					finally
					{
						if (num < 0)
						{
							((IDisposable)luaStackReader/*cast due to .constrained prefix*/).Dispose();
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(result2);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <GetTableAsync>d__25 : IAsyncStateMachine
		{
			public int <>1__state;

			public LightAsyncValueTaskMethodBuilder<LuaValue> <>t__builder;

			public LuaValue table;

			public LuaValue key;

			public LuaState state;

			public CancellationToken cancellationToken;

			private ValueTaskAwaiter<LuaValue> <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				LuaValue result2;
				try
				{
					ValueTaskAwaiter<LuaValue> awaiter;
					if (num == 0)
					{
						awaiter = <>u__1;
						<>u__1 = default(ValueTaskAwaiter<LuaValue>);
						num = (<>1__state = -1);
						goto IL_009f;
					}
					if (!table.TryReadTable(out LuaTable result) || !result.TryGetValue(key, out var value))
					{
						awaiter = LuaVirtualMachine.ExecuteGetTableSlowPath(state, table, key, cancellationToken).GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = awaiter;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
							return;
						}
						goto IL_009f;
					}
					result2 = value;
					goto end_IL_0007;
					IL_009f:
					result2 = awaiter.GetResult();
					end_IL_0007:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(result2);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		public static async ValueTask<LuaClosure> LoadFileAsync(this LuaState state, string fileName, string mode, LuaTable? environment, CancellationToken cancellationToken)
		{
			string name = "@" + fileName;
			using ILuaStream stream = await state.GlobalState.Platform.FileSystem.Open(fileName, LuaFileOpenMode.Read, cancellationToken);
			LuaClosure result;
			if (stream is ILuaByteStream byteStream)
			{
				int num = await byteStream.ReadByteAsync(cancellationToken);
				if (num != 27 && !mode.Contains('t'))
				{
					throw new Exception("attempt to load a text chunk (mode is 'b')");
				}
				if (num < 0)
				{
					result = state.Load(ReadOnlySpan<byte>.Empty, name, mode, environment);
				}
				else
				{
					using ArrayPoolBufferWriter<byte> source = new ArrayPoolBufferWriter<byte>();
					source.GetSpan(1)[0] = (byte)num;
					source.Advance(1);
					await byteStream.ReadBytesAsync(source, cancellationToken);
					result = state.Load(source.WrittenSpan, name, mode, environment);
				}
			}
			else
			{
				if (!mode.Contains('t'))
				{
					throw new Exception("attempt to load a text chunk (mode is 'b')");
				}
				result = state.Load(await stream.ReadAllAsync(cancellationToken), name, environment);
			}
			return result;
		}

		public static ValueTask<int> DoStringAsync(this LuaState state, string source, Memory<LuaValue> results, string? chunkName = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName ?? source);
			return state.ExecuteAsync(closure, results, cancellationToken);
		}

		public static ValueTask<LuaValue[]> DoStringAsync(this LuaState state, string source, string? chunkName = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName ?? source);
			return state.ExecuteAsync(closure, cancellationToken);
		}

		public static ValueTask<int> ExecuteAsync(this LuaState state, ReadOnlySpan<byte> source, Memory<LuaValue> results, string chunkName, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName);
			return state.ExecuteAsync(closure, results, cancellationToken);
		}

		public static ValueTask<LuaValue[]> ExecuteAsync(this LuaState state, ReadOnlySpan<byte> source, string chunkName, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName);
			return state.ExecuteAsync(closure, cancellationToken);
		}

		[AsyncStateMachine(typeof(<DoFileAsync>d__5))]
		[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
		public static ValueTask<int> DoFileAsync(this LuaState state, string path, Memory<LuaValue> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			<DoFileAsync>d__5 stateMachine = default(<DoFileAsync>d__5);
			stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<int>.Create();
			stateMachine.state = state;
			stateMachine.path = path;
			stateMachine.buffer = buffer;
			stateMachine.cancellationToken = cancellationToken;
			stateMachine.<>1__state = -1;
			stateMachine.<>t__builder.Start(ref stateMachine);
			return stateMachine.<>t__builder.Task;
		}

		[AsyncStateMachine(typeof(<DoFileAsync>d__6))]
		[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
		public static ValueTask<LuaValue[]> DoFileAsync(this LuaState state, string path, CancellationToken cancellationToken = default(CancellationToken))
		{
			<DoFileAsync>d__6 stateMachine = default(<DoFileAsync>d__6);
			stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<LuaValue[]>.Create();
			stateMachine.state = state;
			stateMachine.path = path;
			stateMachine.cancellationToken = cancellationToken;
			stateMachine.<>1__state = -1;
			stateMachine.<>t__builder.Start(ref stateMachine);
			return stateMachine.<>t__builder.Task;
		}

		[AsyncStateMachine(typeof(<ExecuteAsync>d__7))]
		[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
		public static ValueTask<int> ExecuteAsync(this LuaState state, LuaClosure closure, Memory<LuaValue> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			<ExecuteAsync>d__7 stateMachine = default(<ExecuteAsync>d__7);
			stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<int>.Create();
			stateMachine.state = state;
			stateMachine.closure = closure;
			stateMachine.buffer = buffer;
			stateMachine.cancellationToken = cancellationToken;
			stateMachine.<>1__state = -1;
			stateMachine.<>t__builder.Start(ref stateMachine);
			return stateMachine.<>t__builder.Task;
		}

		[AsyncStateMachine(typeof(<ExecuteAsync>d__8))]
		[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
		public static ValueTask<LuaValue[]> ExecuteAsync(this LuaState state, LuaClosure closure, CancellationToken cancellationToken = default(CancellationToken))
		{
			<ExecuteAsync>d__8 stateMachine = default(<ExecuteAsync>d__8);
			stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<LuaValue[]>.Create();
			stateMachine.state = state;
			stateMachine.closure = closure;
			stateMachine.cancellationToken = cancellationToken;
			stateMachine.<>1__state = -1;
			stateMachine.<>t__builder.Start(ref stateMachine);
			return stateMachine.<>t__builder.Task;
		}

		public static void Push(this LuaState state, LuaValue value)
		{
			state.Stack.Push(value);
		}

		public static void Push(this LuaState state, [ParamCollection] scoped ReadOnlySpan<LuaValue> span)
		{
			state.Stack.PushRange(span);
		}

		public static void Pop(this LuaState state, int count)
		{
			state.Stack.Pop(count);
		}

		public static LuaValue Pop(this LuaState state)
		{
			return state.Stack.Pop();
		}

		public static LuaStackReader ReadStack(this LuaState state, int argumentCount)
		{
			LuaStack stack = state.Stack;
			return new LuaStackReader(stack, stack.Count - argumentCount);
		}

		public static ValueTask<LuaValue> AddAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result + result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Add, cancellationToken);
		}

		public static ValueTask<LuaValue> SubAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result - result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Sub, cancellationToken);
		}

		public static ValueTask<LuaValue> MulAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result * result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Mul, cancellationToken);
		}

		public static ValueTask<LuaValue> DivAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result / result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Div, cancellationToken);
		}

		public static ValueTask<LuaValue> ModAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(LuaVirtualMachine.Mod(result, result2));
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Mod, cancellationToken);
		}

		public static ValueTask<LuaValue> PowAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(Math.Pow(result, result2));
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Pow, cancellationToken);
		}

		public static ValueTask<LuaValue> UnmAsync(this LuaState state, LuaValue value, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (value.TryReadDouble(out var result))
			{
				return new ValueTask<LuaValue>(0.0 - result);
			}
			return LuaVirtualMachine.ExecuteUnaryOperationMetaMethod(state, value, OpCode.Unm, cancellationToken);
		}

		public static ValueTask<LuaValue> LenAsync(this LuaState state, LuaValue value, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (value.TryReadString(out string result))
			{
				return new ValueTask<LuaValue>(result.Length);
			}
			if (value.TryReadTable(out LuaTable result2))
			{
				return new ValueTask<LuaValue>(result2.ArrayLength);
			}
			return LuaVirtualMachine.ExecuteUnaryOperationMetaMethod(state, value, OpCode.Len, cancellationToken);
		}

		public static ValueTask<bool> LessThanAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadNumber(out var result) && y.TryReadNumber(out var result2))
			{
				return new ValueTask<bool>(result < result2);
			}
			if (x.TryReadString(out string result3) && y.TryReadString(out string result4))
			{
				return new ValueTask<bool>(StringComparer.Ordinal.Compare(result3, result4) < 0);
			}
			return LuaVirtualMachine.ExecuteCompareOperationMetaMethod(state, x, y, OpCode.Lt, cancellationToken);
		}

		public static ValueTask<bool> LessThanOrEqualsAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadNumber(out var result) && y.TryReadNumber(out var result2))
			{
				return new ValueTask<bool>(result <= result2);
			}
			if (x.TryReadString(out string result3) && y.TryReadString(out string result4))
			{
				return new ValueTask<bool>(StringComparer.Ordinal.Compare(result3, result4) <= 0);
			}
			return LuaVirtualMachine.ExecuteCompareOperationMetaMethod(state, x, y, OpCode.Le, cancellationToken);
		}

		public static ValueTask<bool> EqualsAsync(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x == y)
			{
				return new ValueTask<bool>(result: true);
			}
			return LuaVirtualMachine.ExecuteCompareOperationMetaMethod(state, x, y, OpCode.Eq, cancellationToken);
		}

		[AsyncStateMachine(typeof(<GetTableAsync>d__25))]
		[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
		public static ValueTask<LuaValue> GetTableAsync(this LuaState state, LuaValue table, LuaValue key, CancellationToken cancellationToken = default(CancellationToken))
		{
			<GetTableAsync>d__25 stateMachine = default(<GetTableAsync>d__25);
			stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<LuaValue>.Create();
			stateMachine.state = state;
			stateMachine.table = table;
			stateMachine.key = key;
			stateMachine.cancellationToken = cancellationToken;
			stateMachine.<>1__state = -1;
			stateMachine.<>t__builder.Start(ref stateMachine);
			return stateMachine.<>t__builder.Task;
		}

		public static ValueTask SetTableAsync(this LuaState state, LuaValue table, LuaValue key, LuaValue value, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (key.TryReadNumber(out var result) && double.IsNaN(result))
			{
				throw new LuaRuntimeException(state, "table index is NaN");
			}
			if (table.TryReadTable(out LuaTable result2))
			{
				ref LuaValue reference = ref result2.FindValue(key);
				if (!Unsafe.IsNullRef(in reference) && reference.Type != LuaValueType.Nil)
				{
					reference = value;
					return default(ValueTask);
				}
			}
			return LuaVirtualMachine.ExecuteSetTableSlowPath(state, table, key, value, cancellationToken);
		}

		public static ValueTask<LuaValue> ConcatAsync(this LuaState state, ReadOnlySpan<LuaValue> values, CancellationToken cancellationToken = default(CancellationToken))
		{
			state.Stack.PushRange(values);
			return state.ConcatAsync(values.Length, cancellationToken);
		}

		public static ValueTask<LuaValue> ConcatAsync(this LuaState state, int concatCount, CancellationToken cancellationToken = default(CancellationToken))
		{
			return LuaVirtualMachine.Concat(state, concatCount, cancellationToken);
		}

		public static ValueTask<int> CallAsync(this LuaState state, int funcIndex, CancellationToken cancellationToken = default(CancellationToken))
		{
			return LuaVirtualMachine.Call(state, funcIndex, funcIndex, cancellationToken);
		}

		public static ValueTask<int> CallAsync(this LuaState state, int funcIndex, int returnBase, CancellationToken cancellationToken = default(CancellationToken))
		{
			return LuaVirtualMachine.Call(state, funcIndex, returnBase, cancellationToken);
		}

		public static ValueTask<LuaValue[]> CallAsync(this LuaState state, LuaValue function, ReadOnlySpan<LuaValue> arguments, CancellationToken cancellationToken = default(CancellationToken))
		{
			int count = state.Stack.Count;
			state.Stack.Push(function);
			state.Stack.PushRange(arguments);
			return Impl(state, count, cancellationToken);
			[AsyncStateMachine(typeof(<<CallAsync>g__Impl|31_0>d))]
			[AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
			static ValueTask<LuaValue[]> Impl(LuaState state2, int funcIndex, CancellationToken cancellationToken2)
			{
				<<CallAsync>g__Impl|31_0>d stateMachine = default(<<CallAsync>g__Impl|31_0>d);
				stateMachine.<>t__builder = LightAsyncValueTaskMethodBuilder<LuaValue[]>.Create();
				stateMachine.state = state2;
				stateMachine.funcIndex = funcIndex;
				stateMachine.cancellationToken = cancellationToken2;
				stateMachine.<>1__state = -1;
				stateMachine.<>t__builder.Start(ref stateMachine);
				return stateMachine.<>t__builder.Task;
			}
		}
	}
	public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>, IEnumerable
	{
		public struct LuaTableEnumerator : IEnumerator<KeyValuePair<LuaValue, LuaValue>>, IEnumerator, IDisposable
		{
			private int index;

			private readonly int version;

			private KeyValuePair<LuaValue, LuaValue> current;

			public KeyValuePair<LuaValue, LuaValue> Current => current;

			object IEnumerator.Current => Current;

			public LuaTableEnumerator(LuaTable table)
			{
				<table>P = table;
				index = -1;
				version = <table>P.dictionary.Version;
				current = default(KeyValuePair<LuaValue, LuaValue>);
			}

			public bool MoveNext()
			{
				if (index < 0)
				{
					int num = -index - 1;
					Span<LuaValue> span = <table>P.array.AsSpan(num);
					for (int i = 0; i < span.Length; i++)
					{
						if (span[i].Type != LuaValueType.Nil)
						{
							current = new KeyValuePair<LuaValue, LuaValue>(num + i + 1, span[i]);
							index = -num - i - 2;
							return true;
						}
					}
					index = 0;
				}
				while (LuaValueDictionary.MoveNext(<table>P.Dictionary, version, ref index, out current) && current.Value.Type == LuaValueType.Nil)
				{
				}
				return current.Value.Type != LuaValueType.Nil;
			}

			public void Reset()
			{
			}

			public void Dispose()
			{
			}
		}

		private LuaValue[] array;

		private readonly LuaValueDictionary dictionary;

		private LuaTable? metatable;

		private const int MaxArraySize = 16777216;

		pr

Lua.Annotations.dll

Decompiled 4 days ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("nuskey;Akeit0")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Yusuke Nakada")]
[assembly: AssemblyDescription("Attributes for Lua-CSharp SourceGenerator")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d9fb336931d2dc874c924575cc15d9c2d35841ce")]
[assembly: AssemblyProduct("Lua.Annotations")]
[assembly: AssemblyTitle("Lua.Annotations")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/nuskey8/Lua-CSharp")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Lua
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class LuaObjectAttribute : Attribute
	{
		public string? Name { get; }

		public LuaObjectAttribute()
		{
		}

		public LuaObjectAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field)]
	public sealed class LuaMemberAttribute : Attribute
	{
		public string? Name { get; }

		public LuaMemberAttribute()
		{
		}

		public LuaMemberAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class LuaMetamethodAttribute(LuaObjectMetamethod metamethod) : Attribute()
	{
		public LuaObjectMetamethod Metamethod { get; } = metamethod;
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field)]
	public sealed class LuaIgnoreMemberAttribute : Attribute
	{
	}
	public enum LuaObjectMetamethod
	{
		Add,
		Sub,
		Mul,
		Div,
		Mod,
		Pow,
		Unm,
		Len,
		Eq,
		Lt,
		Le,
		Call,
		Concat,
		Pairs,
		IPairs,
		ToString,
		Index,
		NewIndex
	}
}

Microsoft.Bcl.TimeProvider.dll

Decompiled 4 days ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using FxResources.Microsoft.Bcl.TimeProvider;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.TimeProvider")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides support for system time abstraction primitives for .NET Framework and .NET Standard.\r\n\r\nCommonly Used Types:\r\nSystem.TimeProvider\r\nSystem.ITimer")]
[assembly: AssemblyFileVersion("8.0.23.53103")]
[assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.TimeProvider")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("8.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.Microsoft.Bcl.TimeProvider
{
	internal static class SR
	{
	}
}
namespace System
{
	public abstract class TimeProvider
	{
		private sealed class SystemTimeProviderTimer : ITimer, IDisposable, IAsyncDisposable
		{
			private sealed class TimerState
			{
				public TimerCallback Callback { get; }

				public object State { get; }

				public Timer Timer { get; set; }

				public TimerState(TimerCallback callback, object state)
				{
					Callback = callback;
					State = state;
					base..ctor();
				}
			}

			private readonly Timer _timer;

			public SystemTimeProviderTimer(TimeSpan dueTime, TimeSpan period, TimerCallback callback, object state)
			{
				TimerState timerState = new TimerState(callback, state);
				timerState.Timer = (_timer = new Timer(delegate(object s)
				{
					TimerState timerState2 = (TimerState)s;
					timerState2.Callback(timerState2.State);
				}, timerState, dueTime, period));
			}

			public bool Change(TimeSpan dueTime, TimeSpan period)
			{
				try
				{
					return _timer.Change(dueTime, period);
				}
				catch (ObjectDisposedException)
				{
					return false;
				}
			}

			public void Dispose()
			{
				_timer.Dispose();
			}

			public ValueTask DisposeAsync()
			{
				_timer.Dispose();
				return default(ValueTask);
			}
		}

		private sealed class SystemTimeProvider : TimeProvider
		{
			internal SystemTimeProvider()
			{
			}
		}

		private static readonly long s_minDateTicks;

		private static readonly long s_maxDateTicks;

		public static TimeProvider System { get; } = new SystemTimeProvider();


		public virtual TimeZoneInfo LocalTimeZone => TimeZoneInfo.Local;

		public virtual long TimestampFrequency => Stopwatch.Frequency;

		public virtual DateTimeOffset GetUtcNow()
		{
			return DateTimeOffset.UtcNow;
		}

		public DateTimeOffset GetLocalNow()
		{
			DateTimeOffset utcNow = GetUtcNow();
			TimeZoneInfo localTimeZone = LocalTimeZone;
			if (localTimeZone == null)
			{
				throw new InvalidOperationException(global::System.SR.InvalidOperation_TimeProviderNullLocalTimeZone);
			}
			TimeSpan utcOffset = localTimeZone.GetUtcOffset(utcNow);
			if (utcOffset.Ticks == 0L)
			{
				return utcNow;
			}
			long num = utcNow.Ticks + utcOffset.Ticks;
			if ((ulong)num > (ulong)s_maxDateTicks)
			{
				num = ((num < s_minDateTicks) ? s_minDateTicks : s_maxDateTicks);
			}
			return new DateTimeOffset(num, utcOffset);
		}

		public virtual long GetTimestamp()
		{
			return Stopwatch.GetTimestamp();
		}

		public TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp)
		{
			long timestampFrequency = TimestampFrequency;
			if (timestampFrequency <= 0)
			{
				throw new InvalidOperationException(global::System.SR.InvalidOperation_TimeProviderInvalidTimestampFrequency);
			}
			return new TimeSpan((long)((double)(endingTimestamp - startingTimestamp) * (10000000.0 / (double)timestampFrequency)));
		}

		public TimeSpan GetElapsedTime(long startingTimestamp)
		{
			return GetElapsedTime(startingTimestamp, GetTimestamp());
		}

		public virtual ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
		{
			if (callback == null)
			{
				throw new ArgumentNullException("callback");
			}
			return new SystemTimeProviderTimer(dueTime, period, callback, state);
		}

		static TimeProvider()
		{
			DateTime minValue = DateTime.MinValue;
			s_minDateTicks = minValue.Ticks;
			minValue = DateTime.MaxValue;
			s_maxDateTicks = minValue.Ticks;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentOutOfRange_Generic_MustBeNonNegativeNonZero => GetResourceString("ArgumentOutOfRange_Generic_MustBeNonNegativeNonZero");

		internal static string ArgumentOutOfRange_Generic_MustBeGreaterOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeGreaterOrEqual");

		internal static string ArgumentOutOfRange_Generic_MustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeLessOrEqual");

		internal static string InvalidOperation_TimeProviderNullLocalTimeZone => GetResourceString("InvalidOperation_TimeProviderNullLocalTimeZone");

		internal static string InvalidOperation_TimeProviderInvalidTimestampFrequency => GetResourceString("InvalidOperation_TimeProviderInvalidTimestampFrequency");

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Threading
{
	public interface ITimer : IDisposable, IAsyncDisposable
	{
		bool Change(TimeSpan dueTime, TimeSpan period);
	}
}
namespace System.Threading.Tasks
{
	public static class TimeProviderTaskExtensions
	{
		private sealed class DelayState : TaskCompletionSource<bool>
		{
			public ITimer Timer { get; set; }

			public CancellationToken CancellationToken { get; }

			public CancellationTokenRegistration Registration { get; set; }

			public DelayState(CancellationToken cancellationToken)
			{
				CancellationToken = cancellationToken;
			}
		}

		private sealed class WaitAsyncState : TaskCompletionSource<bool>
		{
			public readonly CancellationTokenSource ContinuationCancellation = new CancellationTokenSource();

			public CancellationTokenRegistration Registration;

			public ITimer Timer;

			public CancellationToken CancellationToken { get; }

			public WaitAsyncState(CancellationToken cancellationToken)
				: base(TaskCreationOptions.RunContinuationsAsynchronously)
			{
				CancellationToken = cancellationToken;
			}
		}

		public static Task Delay(this TimeProvider timeProvider, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (timeProvider == TimeProvider.System)
			{
				return Task.Delay(delay, cancellationToken);
			}
			if (timeProvider == null)
			{
				throw new ArgumentNullException("timeProvider");
			}
			if (delay != Timeout.InfiniteTimeSpan && delay < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("delay");
			}
			if (delay == TimeSpan.Zero)
			{
				return Task.CompletedTask;
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			DelayState delayState2 = new DelayState(cancellationToken);
			delayState2.Timer = timeProvider.CreateTimer(delegate(object delayState)
			{
				DelayState delayState5 = (DelayState)delayState;
				delayState5.TrySetResult(result: true);
				delayState5.Registration.Dispose();
				delayState5.Timer?.Dispose();
			}, delayState2, delay, Timeout.InfiniteTimeSpan);
			delayState2.Registration = cancellationToken.Register(delegate(object delayState)
			{
				DelayState delayState3 = (DelayState)delayState;
				ThreadPool.UnsafeQueueUserWorkItem(delegate(object state)
				{
					DelayState delayState4 = (DelayState)state;
					delayState4.TrySetCanceled(delayState4.CancellationToken);
				}, delayState3);
				delayState3.Registration.Dispose();
				delayState3.Timer?.Dispose();
			}, delayState2);
			if (delayState2.Task.IsCompleted)
			{
				delayState2.Registration.Dispose();
				delayState2.Timer.Dispose();
			}
			return delayState2.Task;
		}

		public static Task WaitAsync(this Task task, TimeSpan timeout, TimeProvider timeProvider, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (task == null)
			{
				throw new ArgumentNullException("task");
			}
			if (timeout != Timeout.InfiniteTimeSpan && timeout < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("timeout");
			}
			if (timeProvider == null)
			{
				throw new ArgumentNullException("timeProvider");
			}
			if (task.IsCompleted)
			{
				return task;
			}
			if (timeout == Timeout.InfiniteTimeSpan && !cancellationToken.CanBeCanceled)
			{
				return task;
			}
			if (timeout == TimeSpan.Zero)
			{
				Task.FromException(new TimeoutException());
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			WaitAsyncState waitAsyncState = new WaitAsyncState(cancellationToken);
			waitAsyncState.Timer = timeProvider.CreateTimer(delegate(object s)
			{
				WaitAsyncState waitAsyncState4 = (WaitAsyncState)s;
				waitAsyncState4.TrySetException(new TimeoutException());
				waitAsyncState4.Registration.Dispose();
				waitAsyncState4.Timer?.Dispose();
				waitAsyncState4.ContinuationCancellation.Cancel();
			}, waitAsyncState, timeout, Timeout.InfiniteTimeSpan);
			task.ContinueWith(delegate(Task t, object s)
			{
				WaitAsyncState waitAsyncState3 = (WaitAsyncState)s;
				if (t.IsFaulted)
				{
					waitAsyncState3.TrySetException(t.Exception.InnerExceptions);
				}
				else if (t.IsCanceled)
				{
					waitAsyncState3.TrySetCanceled();
				}
				else
				{
					waitAsyncState3.TrySetResult(result: true);
				}
				waitAsyncState3.Registration.Dispose();
				waitAsyncState3.Timer?.Dispose();
			}, waitAsyncState, waitAsyncState.ContinuationCancellation.Token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
			waitAsyncState.Registration = cancellationToken.Register(delegate(object s)
			{
				WaitAsyncState waitAsyncState2 = (WaitAsyncState)s;
				waitAsyncState2.TrySetCanceled(waitAsyncState2.CancellationToken);
				waitAsyncState2.Timer?.Dispose();
				waitAsyncState2.ContinuationCancellation.Cancel();
			}, waitAsyncState);
			if (waitAsyncState.Task.IsCompleted)
			{
				waitAsyncState.Registration.Dispose();
				waitAsyncState.Timer.Dispose();
			}
			return waitAsyncState.Task;
		}

		public static async Task<TResult> WaitAsync<TResult>(this Task<TResult> task, TimeSpan timeout, TimeProvider timeProvider, CancellationToken cancellationToken = default(CancellationToken))
		{
			await ((Task)task).WaitAsync(timeout, timeProvider, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			return task.Result;
		}

		public static CancellationTokenSource CreateCancellationTokenSource(this TimeProvider timeProvider, TimeSpan delay)
		{
			if (timeProvider == null)
			{
				throw new ArgumentNullException("timeProvider");
			}
			if (delay != Timeout.InfiniteTimeSpan && delay < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("delay");
			}
			if (timeProvider == TimeProvider.System)
			{
				return new CancellationTokenSource(delay);
			}
			CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
			ITimer state = timeProvider.CreateTimer(delegate(object s)
			{
				try
				{
					((CancellationTokenSource)s).Cancel();
				}
				catch (ObjectDisposedException)
				{
				}
			}, cancellationTokenSource, delay, Timeout.InfiniteTimeSpan);
			cancellationTokenSource.Token.Register(delegate(object t)
			{
				((ITimer)t).Dispose();
			}, state);
			return cancellationTokenSource;
		}
	}
}

System.Runtime.CompilerServices.Unsafe.dll

Decompiled 4 days ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyFileVersion("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("6.0.0.0")]
namespace System.Runtime.CompilerServices
{
	public static class Unsafe
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void SkipInit<T>(out T value)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static IntPtr ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}