diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/AddressableAssetSettings.asset b/src/Lua.Unity/Assets/AddressableAssetsData/AddressableAssetSettings.asset index 43ab1777..7f1b0391 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/AddressableAssetSettings.asset +++ b/src/Lua.Unity/Assets/AddressableAssetsData/AddressableAssetSettings.asset @@ -12,10 +12,10 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 468a46d0ae32c3544b7d98094e6448a9, type: 3} m_Name: AddressableAssetSettings m_EditorClassIdentifier: - m_DefaultGroup: 2a0e06d9ccf214f8fa1ca5d1510af7d2 + m_DefaultGroup: d88070ff273c67a47aa61b1ac322925e m_currentHash: serializedVersion: 2 - Hash: 00000000000000000000000000000000 + Hash: 0541ae50fa90e8e78e8bf32544e171fd m_OptimizeCatalogSize: 0 m_BuildRemoteCatalog: 0 m_CatalogRequestsTimeout: 0 @@ -24,11 +24,11 @@ MonoBehaviour: m_InternalBundleIdMode: 1 m_AssetLoadMode: 0 m_BundledAssetProviderType: - m_AssemblyName: - m_ClassName: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.BundledAssetProvider m_AssetBundleProviderType: - m_AssemblyName: - m_ClassName: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.AssetBundleProvider m_IgnoreUnsupportedFilesInBuild: 0 m_UniqueBundleIds: 0 m_EnableJsonCatalog: 0 @@ -60,6 +60,7 @@ MonoBehaviour: m_overridePlayerVersion: '[UnityEditor.PlayerSettings.bundleVersion]' m_GroupAssets: - {fileID: 11400000, guid: 30f1ec4a0d3c9473d9b32a1b02474847, type: 2} + - {fileID: 11400000, guid: 1561a30b342064fa4896f0bfbf686fcb, type: 2} m_BuildSettings: m_LogResourceManagerExceptions: 1 m_BundleBuildPath: Temp/com.unity.addressables/AssetBundles @@ -108,7 +109,7 @@ MonoBehaviour: m_ClassName: m_ActivePlayerDataBuilderIndex: 2 m_DataBuilders: - - {fileID: 11400000, guid: d6921a29df7234327863bccd63d917f6, type: 2} - - {fileID: 11400000, guid: 703d4c54c8176478e87c027f44a5424e, type: 2} - - {fileID: 11400000, guid: 276c7bc6c400449ed930dde9a70d1e70, type: 2} + - {fileID: 11400000, guid: 0618f16a59fed47c1933ae8dde25092a, type: 2} + - {fileID: 11400000, guid: e4575ed4ef1a746ccb1d0fba41ecd093, type: 2} + - {fileID: 11400000, guid: 5f12744ea547f4fe8b261b427250778b, type: 2} m_ActiveProfileId: 1d0a56529a3514cf1aebb59dc61a2305 diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset index a2d46b31..76e26e44 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset +++ b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset @@ -13,16 +13,16 @@ MonoBehaviour: m_Name: Default Local Group m_EditorClassIdentifier: m_GroupName: Default Local Group - m_GUID: 2a0e06d9ccf214f8fa1ca5d1510af7d2 + m_GUID: d88070ff273c67a47aa61b1ac322925e m_SerializeEntries: - - m_GUID: c611eb631438746b991def52ebe74776 + - m_GUID: 16a50852a63da4d0d9221dcb9b74c48c m_Address: bar m_ReadOnly: 0 m_SerializedLabels: [] FlaggedDuringContentUpdateRestriction: 0 m_ReadOnly: 0 - m_Settings: {fileID: 11400000, guid: f1d773be05107486d85b5a324c1c2fb0, type: 2} + m_Settings: {fileID: 11400000, guid: a0f4200005a8343fa9cfda7e23be8a93, type: 2} m_SchemaSet: m_Schemas: - - {fileID: 11400000, guid: 1476390b038364f2f800595d61171b27, type: 2} - - {fileID: 11400000, guid: 7ebbf8a9fd56642d283eb1ef4c8ccf85, type: 2} + - {fileID: 11400000, guid: a90139adc8865497d8309c82638492b0, type: 2} + - {fileID: 11400000, guid: f83e7898558224636ac47d66c1d5f91d, type: 2} diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta index 22b6929d..3467d861 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta +++ b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta @@ -2,7 +2,7 @@ fileFormatVersion: 2 guid: 1561a30b342064fa4896f0bfbf686fcb NativeFormatImporter: externalObjects: {} - mainObjectFileID: 0 + mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant: diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset index 751d5144..633910b9 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset +++ b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset @@ -12,7 +12,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: e5d17a21594effb4e9591490b009e7aa, type: 3} m_Name: Default Local Group_BundledAssetGroupSchema m_EditorClassIdentifier: - m_Group: {fileID: 11400000, guid: 30f1ec4a0d3c9473d9b32a1b02474847, type: 2} + m_Group: {fileID: 11400000, guid: 1561a30b342064fa4896f0bfbf686fcb, type: 2} m_InternalBundleIdMode: 1 m_Compression: 1 m_IncludeAddressInCatalog: 1 diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset index 456d2bd9..dcf8e40f 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset +++ b/src/Lua.Unity/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset @@ -12,5 +12,5 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 5834b5087d578d24c926ce20cd31e6d6, type: 3} m_Name: Default Local Group_ContentUpdateGroupSchema m_EditorClassIdentifier: - m_Group: {fileID: 11400000, guid: 30f1ec4a0d3c9473d9b32a1b02474847, type: 2} + m_Group: {fileID: 11400000, guid: 1561a30b342064fa4896f0bfbf686fcb, type: 2} m_StaticContent: 0 diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset b/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset index 73b3da48..be0f83c8 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset +++ b/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset @@ -12,4 +12,4 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 3a189bb168d8d90478a09ea08c2f3d72, type: 3} m_Name: DefaultObject m_EditorClassIdentifier: - m_AddressableAssetSettingsGuid: f1d773be05107486d85b5a324c1c2fb0 + m_AddressableAssetSettingsGuid: a0f4200005a8343fa9cfda7e23be8a93 diff --git a/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset.meta b/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset.meta index 9a8c6b05..169c5367 100644 --- a/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset.meta +++ b/src/Lua.Unity/Assets/AddressableAssetsData/DefaultObject.asset.meta @@ -2,7 +2,7 @@ fileFormatVersion: 2 guid: abb3d975b60334895afa04bc9ef91e68 NativeFormatImporter: externalObjects: {} - mainObjectFileID: 0 + mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant: diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs new file mode 100644 index 00000000..dc60ed4c --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs @@ -0,0 +1,98 @@ +using Lua.CodeAnalysis.Compilation; +using Lua.Runtime; +using System; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; + +namespace Lua.Unity.Editor +{ + [CustomEditor(typeof(LuacAsset))] + public sealed class LuacAssetEditor : UnityEditor.Editor + { + LuacAsset asset; + static StringBuilder sb = new StringBuilder(); + private byte[] bytes; + string prototypeCacheString; + + public override void OnInspectorGUI() + { + if (asset == null) asset = (LuacAsset)serializedObject.targetObject; + if (bytes == null || !asset.bytes.AsSpan().SequenceEqual(bytes)) + { + var prototype = LuaCompiler.UnDump(asset.bytes.AsSpan(), asset.name); + if (sb == null) + sb = new StringBuilder(); + sb.Clear(); + DebugChunk(sb, prototype, 0, 0); + prototypeCacheString = sb.ToString(); + bytes = asset.bytes; + } + + using (new EditorGUI.IndentLevelScope(-1)) + { + EditorGUILayout.TextArea(prototypeCacheString); + } + } + + static void DebugChunk(StringBuilder builder, Prototype chunk, int nestCount, int id) + { + void AppendLine(string line) + { + for (int i = 0; i < nestCount; i++) + { + builder.Append(" "); + } + + builder.AppendLine(line); + } + + if (nestCount == 0) + AppendLine($"Chunk :{chunk.ChunkName}"); + else AppendLine("[" + nestCount + "," + id + "]"); + AppendLine($"Parameters:{chunk.ParameterCount}"); + + AppendLine("Code -------------------------------------"); + var index = 0; + foreach (var inst in chunk.Code) + { + AppendLine($"[{index}]\t{chunk.LineInfo[index]}\t\t{inst}"); + index++; + } + + AppendLine("LocalVariables ---------------------------"); + index = 0; + foreach (var local in chunk.LocalVariables) + { + AppendLine($"[{index}]\t{local.Name}\t{local.StartPc}\t{local.EndPc}"); + index++; + } + + AppendLine("Constants ---------------------------------"); + index = 0; + foreach (var constant in chunk.Constants.ToArray()) + { + AppendLine($"[{index}]\t{Regex.Escape(constant.ToString())}"); + index++; + } + + AppendLine("UpValues -----------------------------------"); + index = 0; + foreach (var upValue in chunk.UpValues.ToArray()) + { + AppendLine($"[{index}]\t{upValue.Name}\t{(upValue.IsLocal ? 1 : 0)}\t{upValue.Index}"); + index++; + } + + builder.AppendLine(); + + var chunkId = 0; + + foreach (var localChunk in chunk.ChildPrototypes) + { + DebugChunk(builder, localChunk, nestCount + 1, chunkId); + chunkId++; + } + } + } +} \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs.meta b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs.meta new file mode 100644 index 00000000..ff1aea7e --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7cb5a3afb8f64363995fb96ba5587c8f +timeCreated: 1749868556 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs new file mode 100644 index 00000000..91cb3534 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs @@ -0,0 +1,32 @@ +using System.IO; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEditor.AssetImporters; +using UnityEngine; + +namespace Lua.Unity.Editor +{ + [ScriptedImporter(1, "luac")] + public sealed class LuacImporter : ScriptedImporter + { + static Texture2D icon; + public override void OnImportAsset(AssetImportContext ctx) + { + var bytes = File.ReadAllBytes(ctx.assetPath); + var asset = ScriptableObject.CreateInstance(); + if (icon == null) + { + icon = Resources.Load("LuaAssetIcon"); + if (icon == null) + { + Debug.LogWarning("LuaAssetIcon not found in Resources. Using default icon."); + icon = EditorGUIUtility.IconContent("ScriptableObject Icon").image as Texture2D; + } + } + EditorGUIUtility.SetIconForObject (asset,icon ); + asset.bytes = bytes; + ctx.AddObjectToAsset("Main", asset); + ctx.SetMainObject(asset); + } + } +} \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs.meta b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs.meta new file mode 100644 index 00000000..ef867930 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d8f9fbd84f8449649b27628ba85a3217 +timeCreated: 1749868371 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/Resources.meta b/src/Lua.Unity/Assets/Lua.Unity/Editor/Resources.meta new file mode 100644 index 00000000..b12f0622 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/Resources.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1d9c4ac6bedc4e7d8f4d5b10742b8e85 +timeCreated: 1749868505 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetIcon.png b/src/Lua.Unity/Assets/Lua.Unity/Editor/Resources/LuaAssetIcon.png similarity index 100% rename from src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetIcon.png rename to src/Lua.Unity/Assets/Lua.Unity/Editor/Resources/LuaAssetIcon.png diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetIcon.png.meta b/src/Lua.Unity/Assets/Lua.Unity/Editor/Resources/LuaAssetIcon.png.meta similarity index 100% rename from src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetIcon.png.meta rename to src/Lua.Unity/Assets/Lua.Unity/Editor/Resources/LuaAssetIcon.png.meta diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs index cc833494..e1f9aeda 100644 --- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs @@ -12,7 +12,7 @@ namespace Lua.Unity { public sealed class AddressablesModuleLoader : ILuaModuleLoader { - readonly Dictionary cache = new(); + readonly Dictionary cache = new(); public bool Exists(string moduleName) { @@ -26,7 +26,8 @@ public async ValueTask LoadAsync(string moduleName, CancellationToken { if (cache.TryGetValue(moduleName, out var asset)) { - return new LuaModule(moduleName, asset.text); + + return asset .GetModule( moduleName); } var asyncOperation = Addressables.LoadAssetAsync(moduleName); @@ -38,7 +39,7 @@ public async ValueTask LoadAsync(string moduleName, CancellationToken } cache.Add(moduleName, asset); - return new LuaModule(moduleName, asset.text); + return asset .GetModule( moduleName); } } internal static class AsyncOperationHandleExtensions diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs index d83f4ec2..24570603 100644 --- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs @@ -2,9 +2,14 @@ namespace Lua.Unity { - public sealed class LuaAsset : ScriptableObject + public sealed class LuaAsset : LuaAssetBase { [SerializeField] internal string text; public string Text => text; + + public override LuaModule GetModule(string searchedName) + { + return new LuaModule(searchedName,text); + } } } \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs new file mode 100644 index 00000000..540835e5 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs @@ -0,0 +1,10 @@ +using UnityEngine; + +namespace Lua.Unity +{ + + public abstract class LuaAssetBase : ScriptableObject + { + public abstract LuaModule GetModule(string searchedName); + } +} \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs.meta b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs.meta new file mode 100644 index 00000000..e7494dcc --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 68f5e96db703412a9d5023a6874176c9 +timeCreated: 1749868448 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs.meta b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs.meta new file mode 100644 index 00000000..7d4ce94d --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 30eb0281e6634717972999b1cd6da5ad +timeCreated: 1749868419 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs index 438b2feb..59f7560d 100644 --- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs @@ -9,13 +9,14 @@ namespace Lua.Unity { public sealed class ResourcesModuleLoader : ILuaModuleLoader { - readonly Dictionary cache = new(); + readonly Dictionary cache = new(); public bool Exists(string moduleName) { + Debug.Log(moduleName); if (cache.TryGetValue(moduleName, out _)) return true; - var asset = Resources.Load(moduleName); + var asset = Resources.Load(moduleName); if (asset == null) return false; cache.Add(moduleName, asset); @@ -26,7 +27,7 @@ public async ValueTask LoadAsync(string moduleName, CancellationToken { if (cache.TryGetValue(moduleName, out var asset)) { - return new LuaModule(moduleName, asset.text); + return asset.GetModule(moduleName); } var request = Resources.LoadAsync(moduleName); @@ -37,10 +38,9 @@ public async ValueTask LoadAsync(string moduleName, CancellationToken throw new LuaModuleNotFoundException(moduleName); } - asset = (LuaAsset)request.asset; + asset = (LuaAssetBase)request.asset; cache.Add(moduleName, asset); - return new LuaModule(moduleName, asset.text); - } + return asset.GetModule(moduleName); } } #if !UNITY_2023_1_OR_NEWER diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs new file mode 100644 index 00000000..d3358752 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs @@ -0,0 +1,48 @@ +using Lua.Platforms; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; + +namespace Lua.Unity +{ + public class UnityApplicationOsEnvironment : ILuaOsEnvironment + { + public UnityApplicationOsEnvironment(Dictionary environmentVariables = null,bool allowToQuitOnExitCall = false) + { + EnvironmentVariables = environmentVariables ?? new Dictionary(); + AllowToQuitOnExitCall = allowToQuitOnExitCall; + } + + + public bool AllowToQuitOnExitCall { get; } + public Dictionary EnvironmentVariables { get; } + + public string GetEnvironmentVariable(string name) + { + if (EnvironmentVariables.TryGetValue(name, out var value)) + { + return value; + } + + return null; + } + + public ValueTask Exit(int exitCode, CancellationToken cancellationToken) + { + if (AllowToQuitOnExitCall) + { + Application.Quit(exitCode); + throw new OperationCanceledException(); + } + else + { + // If quitting is not allowed, we can just throw an exception or log a message. + throw new InvalidOperationException("Application exit is not allowed in this environment."); + } + } + + public double GetTotalProcessorTime() => Time.time; + } +} \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs.meta b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs.meta new file mode 100644 index 00000000..dfb38b72 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2cf920ff7f0f4cff9b392d71c4656d6e +timeCreated: 1749869194 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs new file mode 100644 index 00000000..b515390a --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs @@ -0,0 +1,100 @@ +using Lua.IO; +using System; +using System.Buffers.Text; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Lua.Unity +{ + public class UnityStandardIO : ILuaStandardIO + { + public UnityStandardIO(ILuaStream input = null) + { + if (input != null) + { + Input = input; + } + else + { + Input = new DummyInputStream(); + } + } + + public ILuaStream Input { get; } + public ILuaStream Output { get; } = new DebugLogStream(false); + public ILuaStream Error { get; } = new DebugLogStream(true); + } + + public class DummyInputStream : ILuaStream + { + public bool IsOpen { get; } = true; + public LuaFileOpenMode Mode => LuaFileOpenMode.Read; + + public ValueTask ReadAllAsync(CancellationToken cancellationToken) + { + // Simulate reading all input from the console + UnityEngine.Debug.Log("Reading all input (simulated)"); + return new ValueTask(("input")); + } + + public ValueTask ReadLineAsync(CancellationToken cancellationToken) + { + // Simulate reading a line from the console + UnityEngine.Debug.Log("Reading a line (simulated)"); + return new ValueTask(default(string)); + } + + public ValueTask ReadStringAsync(int count, CancellationToken cancellationToken) + { + // Simulate reading a specific number of characters from the console + UnityEngine.Debug.Log($"Reading {count} characters (simulated)"); + return new ValueTask(default(string)); + } + + public void Dispose() { } + } + + public class DebugLogStream : ILuaStream + { + public DebugLogStream(bool isError = false) + { + IsError = isError; + } + + public bool IsError { get; } = false; + public bool IsOpen { get; } = true; + public LuaFileOpenMode Mode => LuaFileOpenMode.Write; + + private readonly StringBuilder stringBuilder = new(); + + ValueTask ILuaStream.WriteAsync(ReadOnlyMemory content, CancellationToken cancellationToken) + { + stringBuilder.Append(content.Span); + return default; + } + + ValueTask ILuaStream.FlushAsync(CancellationToken cancellationToken) + { + if (stringBuilder.Length > 0) + { + var message = stringBuilder.ToString(); + if (IsError) + UnityEngine.Debug.LogError(message); + else + UnityEngine.Debug.Log(message); + stringBuilder.Clear(); + } + + return default; + } + + public ValueTask Close(CancellationToken cancellationToken) + { + throw new NotSupportedException("DebugLogStream cannot be closed."); + } + + public void Dispose() { } + } +} \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs.meta b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs.meta new file mode 100644 index 00000000..8f5431c9 --- /dev/null +++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8ba8000b21dc41c4a80569aa46d8a7be +timeCreated: 1749868964 \ No newline at end of file diff --git a/src/Lua.Unity/Assets/Sandbox/SampleScene.unity b/src/Lua.Unity/Assets/Sandbox/SampleScene.unity index 1974db83..2d6944ac 100644 --- a/src/Lua.Unity/Assets/Sandbox/SampleScene.unity +++ b/src/Lua.Unity/Assets/Sandbox/SampleScene.unity @@ -452,7 +452,7 @@ MonoBehaviour: m_GameObject: {fileID: 948832268} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: c59c64163ef484bb6a193121e8fc388c, type: 3} + m_Script: {fileID: 11500000, guid: 52a3185e7d5334f5e9b9e6797db6b6d8, type: 3} m_Name: m_EditorClassIdentifier: --- !u!4 &948832270 diff --git a/src/Lua.Unity/Assets/Sandbox/Sandbox.cs b/src/Lua.Unity/Assets/Sandbox/Sandbox.cs index 3c6f5115..f864418c 100644 --- a/src/Lua.Unity/Assets/Sandbox/Sandbox.cs +++ b/src/Lua.Unity/Assets/Sandbox/Sandbox.cs @@ -1,6 +1,8 @@ using System; using Lua; +using Lua.IO; using Lua.Loaders; +using Lua.Platforms; using Lua.Standard; using Lua.Unity; using UnityEngine; @@ -9,10 +11,15 @@ public class Sandbox : MonoBehaviour { async void Start() { - var state = LuaState.Create(); + var state = LuaState.Create( new LuaPlatform( + fileSystem: new FileSystem(), + osEnvironment: new UnityApplicationOsEnvironment(), + standardIO: new UnityStandardIO(), + timeProvider: TimeProvider.System + )); state.ModuleLoader = CompositeModuleLoader.Create(new AddressablesModuleLoader(), new ResourcesModuleLoader()); state.OpenStandardLibraries(); - state.Environment["print"] = new LuaFunction("print", (context, buffer, ct) => + state.Environment["print"] = new LuaFunction("print", (context, ct) => { Debug.Log(context.GetArgument(0)); return new(0); @@ -25,10 +32,10 @@ await state.DoStringAsync( print('test start') local foo = require 'foo' foo.greet() - local bar = require 'bar' bar.greet() - +require 'test' +os.exit(0) ", cancellationToken: destroyCancellationToken); } catch (Exception ex) diff --git a/src/Lua.Unity/Packages/manifest.json b/src/Lua.Unity/Packages/manifest.json index 7d0fc868..fa23bb24 100644 --- a/src/Lua.Unity/Packages/manifest.json +++ b/src/Lua.Unity/Packages/manifest.json @@ -1,6 +1,7 @@ { "dependencies": { "com.github-glitchenzo.nugetforunity": "https://github.com/GlitchEnzo/NuGetForUnity.git?path=/src/NuGetForUnity", + "com.nuskey8.lua.unity.internal": "file:../../Lua/bin/Debug/netstandard2.1", "com.unity.addressables": "2.2.2", "com.unity.ai.navigation": "2.0.4", "com.unity.collab-proxy": "2.6.0", diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1.meta deleted file mode 100644 index 545bae74..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 416b07e9204db499d88a21b05d4165c9 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/.signature.p7s b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/.signature.p7s deleted file mode 100644 index da43b7a1..00000000 Binary files a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/.signature.p7s and /dev/null differ diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/Icon.png b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/Icon.png deleted file mode 100644 index 765536b6..00000000 Binary files a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/Icon.png and /dev/null differ diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/Icon.png.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/Icon.png.meta deleted file mode 100644 index 9bec59b7..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/Icon.png.meta +++ /dev/null @@ -1,169 +0,0 @@ -fileFormatVersion: 2 -guid: 306665d22a68b49868b3a2bca04fbb1a -TextureImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 13 - mipmaps: - mipMapMode: 0 - enableMipMap: 1 - sRGBTexture: 1 - linearTexture: 0 - fadeOut: 0 - borderMipMap: 0 - mipMapsPreserveCoverage: 0 - alphaTestReferenceValue: 0.5 - mipMapFadeDistanceStart: 1 - mipMapFadeDistanceEnd: 3 - bumpmap: - convertToNormalMap: 0 - externalNormalMap: 0 - heightScale: 0.25 - normalMapFilter: 0 - flipGreenChannel: 0 - isReadable: 0 - streamingMipmaps: 0 - streamingMipmapsPriority: 0 - vTOnly: 0 - ignoreMipmapLimit: 0 - grayScaleToAlpha: 0 - generateCubemap: 6 - cubemapConvolution: 0 - seamlessCubemap: 0 - textureFormat: 1 - maxTextureSize: 2048 - textureSettings: - serializedVersion: 2 - filterMode: 1 - aniso: 1 - mipBias: 0 - wrapU: 0 - wrapV: 0 - wrapW: 0 - nPOTScale: 1 - lightmap: 0 - compressionQuality: 50 - spriteMode: 0 - spriteExtrude: 1 - spriteMeshType: 1 - alignment: 0 - spritePivot: {x: 0.5, y: 0.5} - spritePixelsToUnits: 100 - spriteBorder: {x: 0, y: 0, z: 0, w: 0} - spriteGenerateFallbackPhysicsShape: 1 - alphaUsage: 1 - alphaIsTransparency: 0 - spriteTessellationDetail: -1 - textureType: 0 - textureShape: 1 - singleChannelComponent: 0 - flipbookRows: 1 - flipbookColumns: 1 - maxTextureSizeSet: 0 - compressionQualitySet: 0 - textureFormatSet: 0 - ignorePngGamma: 0 - applyGammaDecoding: 0 - swizzle: 50462976 - cookieLightType: 0 - platformSettings: - - serializedVersion: 4 - buildTarget: DefaultTexturePlatform - maxTextureSize: 2048 - resizeAlgorithm: 0 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - ignorePlatformSupport: 0 - androidETC2FallbackOverride: 0 - forceMaximumCompressionQuality_BC6H_BC7: 0 - - serializedVersion: 4 - buildTarget: WebGL - maxTextureSize: 2048 - resizeAlgorithm: 0 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - ignorePlatformSupport: 0 - androidETC2FallbackOverride: 0 - forceMaximumCompressionQuality_BC6H_BC7: 0 - - serializedVersion: 4 - buildTarget: Win64 - maxTextureSize: 2048 - resizeAlgorithm: 0 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - ignorePlatformSupport: 0 - androidETC2FallbackOverride: 0 - forceMaximumCompressionQuality_BC6H_BC7: 0 - - serializedVersion: 4 - buildTarget: iOS - maxTextureSize: 2048 - resizeAlgorithm: 0 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - ignorePlatformSupport: 0 - androidETC2FallbackOverride: 0 - forceMaximumCompressionQuality_BC6H_BC7: 0 - - serializedVersion: 4 - buildTarget: Standalone - maxTextureSize: 2048 - resizeAlgorithm: 0 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - ignorePlatformSupport: 0 - androidETC2FallbackOverride: 0 - forceMaximumCompressionQuality_BC6H_BC7: 0 - - serializedVersion: 4 - buildTarget: Android - maxTextureSize: 2048 - resizeAlgorithm: 0 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - ignorePlatformSupport: 0 - androidETC2FallbackOverride: 0 - forceMaximumCompressionQuality_BC6H_BC7: 0 - spriteSheet: - serializedVersion: 2 - sprites: [] - outline: [] - customData: - physicsShape: [] - bones: [] - spriteID: - internalID: 0 - vertices: [] - indices: - edges: [] - weights: [] - secondaryTextures: [] - spriteCustomMetadata: - entries: [] - nameFileIdTable: {} - mipmapLimitGroupName: - pSDRemoveMatte: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/LuaCSharp.nuspec b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/LuaCSharp.nuspec deleted file mode 100644 index 43e75ddd..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/LuaCSharp.nuspec +++ /dev/null @@ -1,24 +0,0 @@ - - - - LuaCSharp - 0.3.1 - Annulus Games - MIT - https://licenses.nuget.org/MIT - Icon.png - README.md - https://github.com/AnnulusGames/Lua-CSharp - High performance Lua interpreter implemented in C# for .NET and Unity - © Annulus Games - lua interpreter - - - - - - - - - - \ No newline at end of file diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/LuaCSharp.nuspec.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/LuaCSharp.nuspec.meta deleted file mode 100644 index adf12c90..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/LuaCSharp.nuspec.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 9852f8b1690074e67a6420f320832008 -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/README.md b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/README.md deleted file mode 100644 index 72dfba95..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/README.md +++ /dev/null @@ -1,519 +0,0 @@ -# Lua-CSharp - -High performance Lua interpreter implemented in C# for .NET and Unity - -![img](docs/Header.png) - -[![NuGet](https://img.shields.io/nuget/v/LuaCSharp.svg)](https://www.nuget.org/packages/LuaCSharp) -[![Releases](https://img.shields.io/github/release/AnnulusGames/Lua-CSharp.svg)](https://github.com/AnnulusGames/Lua-CSharp/releases) -[![license](https://img.shields.io/badge/LICENSE-MIT-green.svg)](LICENSE) - -English | [日本語](README_JA.md) - -## Overview - -Lua-CSharp is a library that provides a Lua interpreter implemented in C#. By integrating Lua-CSharp, you can easily embed Lua scripts into your .NET applications. - -Lua-CSharp leverages the latest C# features, designed with low allocation and high performance in mind. It is optimized to deliver maximum performance when used for interoperation between C# and Lua in C# applications. Below is a benchmark comparison with [MoonSharp](https://github.com/moonsharp-devs/moonsharp/) and [NLua](https://github.com/NLua/NLua): - -![img](docs/Benchmark.png) - -MoonSharp generally provides good speed but incurs significant allocations due to its design. NLua, being a C-binding implementation, is fast, but introduces substantial overhead when interacting with the C# layer. Lua-CSharp, fully implemented in C#, allows for seamless interaction with C# code without additional overhead. Moreover, it operates reliably in AOT environments since it does not rely on IL generation. - -## Features - -* Lua 5.2 interpreter implemented in C# -* Easy-to-use API integrated with async/await -* Support for exception handling with try-catch -* High-performance implementation utilizing modern C# -* Unity support (works with both Mono and IL2CPP) - -## Installation - -### NuGet packages - -To use Lua-CSharp, .NET Standard 2.1 or higher is required. The package can be obtained from NuGet. - -### .NET CLI - -```ps1 -dotnet add package LuaCSharp -``` - -### Package Manager - -```ps1 -Install-Package LuaCSharp -``` - -### Unity - -Lua-CSharp can also be used in Unity (works with both Mono and IL2CPP). - -### Requirements - -* Unity 2021.3 or higher - -### Installation - -1. Install [NugetForUnity](https://github.com/GlitchEnzo/NuGetForUnity). -2. Open the NuGet window by going to `NuGet > Manage NuGet Packages`, search for the `LuaCSharp` package, and install it. - -## Quick Start - -By using the `LuaState` class, you can execute Lua scripts from C#. Below is a sample code that evaluates a simple calculation written in Lua. - -```cs -using Lua; - -// Create a LuaState -var state = LuaState.Create(); - -// Execute a Lua script string with DoStringAsync -var results = await state.DoStringAsync("return 1 + 1"); - -// 2 -Console.WriteLine(results[0]); -``` - -> [!WARNING] -> `LuaState` is not thread-safe. Do not access it from multiple threads simultaneously. - -## LuaValue - -Values in Lua scripts are represented by the `LuaValue` type. The value of a `LuaValue` can be read using `TryRead(out T value)` or `Read()`. - -```cs -var results = await state.DoStringAsync("return 1 + 1"); - -// double -var value = results[0].Read(); -``` - -You can also get the type of the value from the `Type` property. - -```cs -var isNil = results[0].Type == LuaValueType.Nil; -``` - -Below is a table showing the type mapping between Lua and C#. - -| Lua | C# | -| ---------- | ----------------- | -| `nil` | `LuaValue.Nil` | -| `boolean` | `bool` | -| `string` | `string` | -| `number` | `double`, `float` | -| `table` | `LuaTable` | -| `function` | `LuaFunction` | -| `userdata` | `LuaUserData` | -| `thread` | `LuaThread` | - -When creating a `LuaValue` from the C# side, compatible types are implicitly converted into `LuaValue`. - -```cs -LuaValue value; -value = 1.2; // double -> LuaValue -value = "foo"; // string -> LuaValue -value = new LuaTable() // LuaTable -> LuaValue -``` - -## LuaTable - -Lua tables are represented by the `LuaTable` type. They can be used similarly to `LuaValue[]` or `Dictionary`. - -```cs -// Create a table in Lua -var results = await state.DoStringAsync("return { a = 1, b = 2, c = 3 }"); -var table1 = results[0].Read(); - -// 1 -Console.WriteLine(table1["a"]); - -// Create a table in C# -results = await state.DoStringAsync("return { 1, 2, 3 }"); -var table2 = results[0].Read(); - -// 1 (Note: Lua arrays are 1-indexed) -Console.WriteLine(table2[1]); -``` - -## Global Environment - -You can access Lua's global environment through `state.Environment`. This table allows for easy value exchange between Lua and C#. - -```cs -// Set a = 10 -state.Environment["a"] = 10; - -var results = await state.DoStringAsync("return a"); - -// 10 -Console.WriteLine(results[0]); -``` - -## Standard Libraries - -You can use Lua's standard libraries as well. By calling `state.OpenStandardLibraries()`, the standard library tables are added to the `LuaState`. - -```cs -using Lua; -using Lua.Standard; - -var state = LuaState.Create(); - -// Add standard libraries -state.OpenStandardLibraries(); - -var results = await state.DoStringAsync("return math.pi"); -Console.WriteLine(results[0]); // 3.141592653589793 -``` - -For more details on standard libraries, refer to the [Lua official manual](https://www.lua.org/manual/5.2/manual.html#6). - -> [!WARNING] -> Lua-CSharp does not support all functions of the standard libraries. For details, refer to the [Compatibility](#compatibility) section. - -## Functions - -Lua functions are represented by the `LuaFunction` type. With `LuaFunction`, you can call Lua functions from C#, or define functions in C# that can be called from Lua. - -### Calling Lua Functions from C# - -```lua --- lua2cs.lua - -local function add(a, b) - return a + b -end - -return add; -``` - -```cs -var results = await state.DoFileAsync("lua2cs.lua"); -var func = results[0].Read(); - -// Execute the function with arguments -var funcResults = await func.InvokeAsync(state, new[] { 1, 2 }); - -// 3 -Console.WriteLine(funcResults[0]); -``` - -### Calling C# Functions from Lua - -It is possible to create a `LuaFunction` from a lambda expression. - -```cs -// Add the function to the global environment -state.Environment["add"] = new LuaFunction((context, buffer, ct) => -{ - // Get the arguments using context.GetArgument() - var arg0 = context.GetArgument(0); - var arg1 = context.GetArgument(1); - - // Write the return value to the buffer - buffer.Span[0] = arg0 + arg1; - - // Return the number of values - return new(1); -}); - -// Execute a Lua script -var results = await state.DoFileAsync("cs2lua.lua"); - -// 3 -Console.WriteLine(results[i]); -``` - -```lua --- cs2lua.lua - -return add(1, 2) -``` - -> [!TIP] -> Defining functions with `LuaFunction` can be somewhat verbose. When adding multiple functions, it is recommended to use the Source Generator with the `[LuaObject]` attribute. For more details, see the [LuaObject](#luaobject) section. - -## Integration with async/await - -`LuaFunction` operates asynchronously. Therefore, you can define a function that waits for an operation in Lua, such as the example below: - -```cs -// Define a function that waits for the given number of seconds using Task.Delay -state.Environment["wait"] = new LuaFunction(async (context, buffer, ct) => -{ - var sec = context.GetArgument(0); - await Task.Delay(TimeSpan.FromSeconds(sec)); - return 0; -}); - -await state.DoFileAsync("sample.lua"); -``` - -```lua --- sample.lua - -print "hello!" - -wait(1.0) -- wait 1 sec - -print "how are you?" - -wait(1.0) -- wait 1 sec - -print "goodbye!" -``` - -This code can resume the execution of the Lua script after waiting with await, as shown in the following figure. This is very useful when writing scripts to be incorporated into games. - -![img](docs/img1.png) - -## Coroutines - -Lua coroutines are represented by the `LuaThread` type. - -Coroutines can not only be used within Lua scripts, but you can also await Lua-created coroutines from C#. - -```lua --- coroutine.lua - -local co = coroutine.create(function() - for i = 1, 10 do - print(i) - coroutine.yield() - end -end) - -return co -``` - -```cs -var results = await state.DoFileAsync("coroutine.lua"); -var co = results[0].Read(); - -for (int i = 0; i < 10; i++) -{ - var resumeResults = await co.ResumeAsync(state); - - // Similar to coroutine.resume(), returns true on success and the return values afterward - // 1, 2, 3, 4, ... - Console.WriteLine(resumeResults[1]); -} -``` - -## LuaObject - -By applying the `[LuaObject]` attribute, you can create custom classes that run within Lua. Adding this attribute to a class that you wish to use in Lua allows the Source Generator to automatically generate the code required for interaction from Lua. - -The following is an example implementation of a wrapper class for `System.Numerics.Vector3` that can be used in Lua: - -```cs -using System.Numerics; -using Lua; - -var state = LuaState.Create(); - -// Add an instance of the defined LuaObject as a global variable -// (Implicit conversion to LuaValue is automatically defined for classes with the LuaObject attribute) -state.Environment["Vector3"] = new LuaVector3(); - -await state.DoFileAsync("vector3_sample.lua"); - -// Add LuaObject attribute and partial keyword -[LuaObject] -public partial class LuaVector3 -{ - Vector3 vector; - - // Add LuaMember attribute to members that will be used in Lua - // The argument specifies the name used in Lua (if omitted, the member name is used) - [LuaMember("x")] - public float X - { - get => vector.X; - set => vector = vector with { X = value }; - } - - [LuaMember("y")] - public float Y - { - get => vector.Y; - set => vector = vector with { Y = value }; - } - - [LuaMember("z")] - public float Z - { - get => vector.Z; - set => vector = vector with { Z = value }; - } - - // Static methods are treated as regular Lua functions - [LuaMember("create")] - public static LuaVector3 Create(float x, float y, float z) - { - return new LuaVector3() - { - vector = new Vector3(x, y, z) - }; - } - - // Instance methods implicitly receive the instance (this) as the first argument - // In Lua, this is accessed with instance:method() syntax - [LuaMember("normalized")] - public LuaVector3 Normalized() - { - return new LuaVector3() - { - vector = Vector3.Normalize(vector) - }; - } -} -``` - -```lua --- vector3_sample.lua - -local v1 = Vector3.create(1, 2, 3) --- 1 2 3 -print(v1.x, v1.y, v1.z) - -local v2 = v1:normalized() --- 0.26726123690605164 0.5345224738121033 0.8017836809158325 -print(v2.x, v2.y, v2.z) -``` - -The types of fields/properties with the `[LuaMember]` attribute, as well as the argument and return types of methods, must be either `LuaValue` or convertible to/from `LuaValue`. - -Return types such as `void`, `Task/Task`, `ValueTask/ValueTask`, `UniTask/UniTask`, and `Awaitable/Awaitable` are also supported. - -If the type is not supported, the Source Generator will output a compile-time error. - -### LuaMetamethod - -By adding the `[LuaMetamethod]` attribute, you can designate a C# method to be used as a Lua metamethod. - -Here is an example that adds the `__add`, `__sub`, and `__tostring` metamethods to the `LuaVector3` class: - -```cs -[LuaObject] -public partial class LuaVector3 -{ - // The previous implementation is omitted - - [LuaMetamethod(LuaObjectMetamethod.Add)] - public static LuaVector3 Add(LuaVector3 a, LuaVector3 b) - { - return new LuaVector3() - { - vector = a.vector + b.vector - }; - } - - [LuaMetamethod(LuaObjectMetamethod.Sub)] - public static LuaVector3 Sub(LuaVector3 a, LuaVector3 b) - { - return new LuaVector3() - { - vector = a.vector - b.vector - }; - } - - [LuaMetamethod(LuaObjectMetamethod.ToString)] - public override string ToString() - { - return vector.ToString(); - } -} -``` - -```lua -local v1 = Vector3.create(1, 1, 1) -local v2 = Vector3.create(2, 2, 2) - -print(v1) -- <1, 1, 1> -print(v2) -- <2, 2, 2> - -print(v1 + v2) -- <3, 3, 3> -print(v1 - v2) -- <-1, -1, -1> -``` - -> [!NOTE] -> `__index` and `__newindex` cannot be set as they are used internally by the code generated by `[LuaObject]`. - -## Module Loading - -In Lua, you can load modules using the `require` function. In regular Lua, modules are managed by searchers within the `package.searchers` function list. In Lua-CSharp, this is replaced by the `ILuaModuleLoader` interface. - -```cs -public interface ILuaModuleLoader -{ - bool Exists(string moduleName); - ValueTask LoadAsync(string moduleName, CancellationToken cancellationToken = default); -} -``` - -You can set the `LuaState.ModuleLoader` to change how modules are loaded. By default, the `FileModuleLoader` is set to load modules from Lua files. - -You can also combine multiple loaders using `CompositeModuleLoader.Create(loader1, loader2, ...)`. - -```cs -state.ModuleLoader = CompositeModuleLoader.Create( - new FileModuleLoader(), - new CustomModuleLoader() -); -``` - -Loaded modules are cached in the `package.loaded` table, just like regular Lua. This can be accessed via `LuaState.LoadedModules`. - -## Exception Handling - -Lua script parsing errors and runtime exceptions throw exceptions that inherit from `LuaException`. You can catch these to handle errors during execution. - -```cs -try -{ - await state.DoFileAsync("filename.lua"); -} -catch (LuaParseException) -{ - // Handle parsing errors -} -catch (LuaRuntimeException) -{ - // Handle runtime exceptions -} -``` - -## Compatibility - -Lua-CSharp is designed with integration into .NET in mind, so there are several differences from the C implementation. - -### Binary - -Lua-CSharp does not support Lua bytecode (tools like `luac` cannot be used). Only Lua source code can be executed. - -### Character Encoding - -The character encoding used in Lua-CSharp is UTF-16. Since standard Lua assumes a single-byte character encoding, string behavior differs significantly. - -For example, in regular Lua, the following code outputs `15`, but in Lua-CSharp, it outputs `5`. - -```lua -local l = string.len("あいうえお") -print(l) -``` - -All string library functions handle strings as UTF-16. - -### Garbage Collection - -Since Lua-CSharp is implemented in C#, it relies on .NET's garbage collector. As a result, memory management behavior differs from regular Lua. - -While `collectgarbage()` is available, it simply calls the corresponding .NET garbage collection method and may not exhibit the same behavior as C's Lua garbage collector. - -## License - -Lua-CSharp is licensed under the [MIT License](LICENSE). diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/README.md.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/README.md.meta deleted file mode 100644 index a31538a9..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/README.md.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: ca852d91bba6d4f1bb3b51fa9102d995 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers.meta deleted file mode 100644 index 34ab4ad7..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 8d2121deb53d94ca2a244173798b5010 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet.meta deleted file mode 100644 index 5254452d..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: ebee2cd7f5c8c48e6b9592d28d5c0bb8 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs.meta deleted file mode 100644 index eb579750..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c490e8a3c6ca14ba2a2556f3ff493942 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs/Lua.SourceGenerator.dll b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs/Lua.SourceGenerator.dll deleted file mode 100644 index fb88a0ae..00000000 Binary files a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs/Lua.SourceGenerator.dll and /dev/null differ diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs/Lua.SourceGenerator.dll.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs/Lua.SourceGenerator.dll.meta deleted file mode 100644 index 53482f57..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/analyzers/dotnet/cs/Lua.SourceGenerator.dll.meta +++ /dev/null @@ -1,51 +0,0 @@ -fileFormatVersion: 2 -guid: 3d3d5d244d2704fde9e99cd90ebd083f -labels: -- NuGetForUnity -- RoslynAnalyzer -PluginImporter: - externalObjects: {} - serializedVersion: 3 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 1 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - Any: - enabled: 0 - settings: - 'Exclude ': 0 - Exclude Android: 0 - Exclude CloudRendering: 0 - Exclude EmbeddedLinux: 0 - Exclude GameCoreScarlett: 0 - Exclude GameCoreXboxOne: 0 - Exclude Linux64: 0 - Exclude OSXUniversal: 0 - Exclude PS4: 0 - Exclude PS5: 0 - Exclude QNX: 0 - Exclude ReservedCFE: 0 - Exclude Switch: 0 - Exclude VisionOS: 0 - Exclude WebGL: 0 - Exclude Win: 0 - Exclude Win64: 0 - Exclude WindowsStoreApps: 0 - Exclude XboxOne: 0 - Exclude iOS: 0 - Exclude tvOS: 0 - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - WindowsStoreApps: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib.meta deleted file mode 100644 index 17d0cf8b..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 712703d7889d34e3f80f7e11a115306e -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1.meta deleted file mode 100644 index 214344b2..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 6907bd5f6ac8a4472a0145d853426293 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1/Lua.dll b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1/Lua.dll deleted file mode 100644 index f0d4f8cb..00000000 Binary files a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1/Lua.dll and /dev/null differ diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1/Lua.dll.meta b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1/Lua.dll.meta deleted file mode 100644 index 43927c6c..00000000 --- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/LuaCSharp.0.3.1/lib/netstandard2.1/Lua.dll.meta +++ /dev/null @@ -1,29 +0,0 @@ -fileFormatVersion: 2 -guid: 867dfdc624be84676a592048e765a7ff -labels: -- NuGetForUnity -PluginImporter: - externalObjects: {} - serializedVersion: 3 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 1 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - Any: - enabled: 1 - settings: {} - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - WindowsStoreApps: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/Lua.Unity/Packages/nuget-packages/packages.config b/src/Lua.Unity/Packages/nuget-packages/packages.config index fbdd0288..a9d4fdcf 100644 --- a/src/Lua.Unity/Packages/nuget-packages/packages.config +++ b/src/Lua.Unity/Packages/nuget-packages/packages.config @@ -1,5 +1,6 @@  - - + + + \ No newline at end of file diff --git a/src/Lua.Unity/Packages/packages-lock.json b/src/Lua.Unity/Packages/packages-lock.json index f89d3a31..f4bdbb17 100644 --- a/src/Lua.Unity/Packages/packages-lock.json +++ b/src/Lua.Unity/Packages/packages-lock.json @@ -7,6 +7,12 @@ "dependencies": {}, "hash": "242f30ec55ef9c34f1e9953126e6e8350ec3f4c0" }, + "com.nuskey8.lua.unity.internal": { + "version": "file:../../Lua/bin/Debug/netstandard2.1", + "depth": 0, + "source": "local", + "dependencies": {} + }, "com.unity.addressables": { "version": "2.2.2", "depth": 0, diff --git a/src/Lua.Unity/ProjectSettings/EditorBuildSettings.asset b/src/Lua.Unity/ProjectSettings/EditorBuildSettings.asset index be6bb434..2cb387b5 100644 --- a/src/Lua.Unity/ProjectSettings/EditorBuildSettings.asset +++ b/src/Lua.Unity/ProjectSettings/EditorBuildSettings.asset @@ -9,6 +9,6 @@ EditorBuildSettings: path: Assets/Sandbox/SampleScene.unity guid: 99c9720ab356a0642a771bea13969a05 m_configObjects: - com.unity.addressableassets: {fileID: 11400000, guid: 5b124f60b731f48fba10f000d3390a42, type: 2} + com.unity.addressableassets: {fileID: 11400000, guid: abb3d975b60334895afa04bc9ef91e68, type: 2} com.unity.input.settings.actions: {fileID: -944628639613478452, guid: 052faaac586de48259a63d0c4782560b, type: 3} m_UseUCBPForAssetBundles: 0