### Install Luau.Native Package Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Provides commands for installing the Luau.Native NuGet package, which offers direct C API bindings for Luau. Installation methods include using the .NET CLI and the Package Manager. ```PowerShell dotnet add package Luau.Native ``` ```PowerShell Install-Package Luau.Native ``` -------------------------------- ### Install Luau.Native NuGet Package Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Provides commands for installing the `Luau.Native` NuGet package, which offers direct C API bindings for Luau. Includes instructions for both the .NET CLI and Package Manager. ```PowerShell dotnet add package Luau.Native ``` ```PowerShell Install-Package Luau.Native ``` -------------------------------- ### Install Luau .NET Package via .NET CLI Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Installs the Luau NuGet package using the .NET Command Line Interface. This method requires .NET Standard 2.1 or higher. ```powershell dotnet add package Luau ``` -------------------------------- ### Install Luau for .NET CLI Tool Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md This command installs the `luau-cli` global tool using the .NET CLI. It makes the `dotnet luau` command available system-wide for interacting with Luau functionalities. ```ps1 dotnet tool install --global luau-cli ``` -------------------------------- ### Opening All Luau Standard Libraries in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Provides a convenient method to open all available Luau standard libraries at once within a `LuauState` instance. This simplifies setup when a full Luau environment is desired. ```C# state.OpenLibraries(); ``` -------------------------------- ### Open All Luau Standard Libraries Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Shows a convenient method `OpenLibraries()` to enable all available Luau standard libraries on a `LuauState` instance with a single call. This simplifies the setup process when full Luau functionality is desired. ```C# state.OpenLibraries(); ``` -------------------------------- ### Install Luau for .NET CLI Tool Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Provides the command to install the global command-line interface (CLI) tool for Luau for .NET. This tool enables access to various Luau utilities directly from the terminal. ```PowerShell dotnet tool install --global luau-cli ``` -------------------------------- ### Install Luau .NET Package via Package Manager Console Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Installs the Luau NuGet package using the Package Manager Console, typically found in Visual Studio. This method requires .NET Standard 2.1 or higher. ```powershell Install-Package Luau ``` -------------------------------- ### Example of Generated Luau Type Definition File Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Provides an example of the content found within a generated Luau type definition file (`.d.luau`). It illustrates how C# members, defined with `[LuauLibrary]` and `[LuauMember]`, are translated into Luau type declarations. ```Lua -- libs.d.luau declare cmd: { foo: number, Hello: () -> (), echo: (value: string) -> (), } ``` -------------------------------- ### Create and Register Custom Luau Libraries from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Shows how to define a custom Luau library in C# using the `[LuauLibrary]` attribute and expose members with `[LuauMember]`. It includes examples of fields, properties, and static/instance methods. The second part demonstrates how to register this custom library with the Luau state using `OpenLibrary()`. ```C# // Source Generatorによって必要なコードが生成されるため、partialキーワードが必要 [LuauLibrary("foo")] partial class FooLibrary { [LuauMember] public double field = 10; [LuauMember("property")] public double Property { get; set; } = 20; [LuauMember("hello")] public static void Hello() { Console.WriteLine("hello!"); } [LuauMember("echo")] public static void Echo(string value) { Console.WriteLine(value); } [LuauMember("getfield")] public double GetField() { return field; } } ``` ```C# state.OpenLibrary(); ``` -------------------------------- ### Use Luau.Native C API Bindings in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to interact with the Luau C API directly using the `Luau.Native` package. This example shows creating a new Luau state, pushing a number, retrieving its value, and closing the state. ```C# using Luau.Native; using static Luau.Native.NativeMethods; unsafe { lua_State* l = luaL_newstate(); lua_pushnumber(l, 12.3); double v = lua_tonumber(l, -1); lua_pop(l, 1); lua_close(l); } ``` -------------------------------- ### Install Luau Unity Package via Git URL Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Adds the Luau Unity package to a Unity project by specifying its Git repository URL in the Package Manager's 'Add package from git URL' option. ```text https://github.com/nuskey8/luau-dotnet.git?path=src/Luau.Unity/Assets/Luau.Unity ``` -------------------------------- ### Install Luau for .NET using Package Manager Console Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md This command installs the Luau NuGet package via the Package Manager Console, typically found in Visual Studio. It provides an integrated environment for managing NuGet dependencies within the IDE. ```PowerShell Install-Package Luau ``` -------------------------------- ### Install Luau for .NET using .NET CLI Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md This command adds the Luau NuGet package to your .NET project using the .NET Command Line Interface. It's a standard and efficient way to manage project dependencies directly from the terminal. ```PowerShell dotnet add package Luau ``` -------------------------------- ### Define Module Aliases in .luaurc Configuration File (JSON) Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Example of a `.luaurc` JSON configuration file showing how to define aliases. These aliases simplify module paths, making `require` statements more concise and maintainable. ```JSON { "aliases": { "Script": "." } } ``` -------------------------------- ### Encode Strings for HTML, JavaScript, and URLs in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/src/Luau.Unity/Packages/nuget-packages/InstalledPackages/System.Text.Encodings.Web.9.0.6/PACKAGE.md Demonstrates how to use `HtmlEncoder.Default`, `JavaScriptEncoder.Default`, and `UrlEncoder.Default` to safely encode strings for web contexts, preventing common vulnerabilities like XSS. It shows examples for HTML, JavaScript, and URL encoding. ```C# using System.Text.Encodings.Web; string unsafeString = ""; // HTML encode the string to safely display it on a web page. string safeHtml = HtmlEncoder.Default.Encode(unsafeString); Console.WriteLine(safeHtml); // <script>alert('XSS Attack!');</script> // JavaScript encode the string to safely include it in a JavaScript context. string safeJavaScript = JavaScriptEncoder.Default.Encode(unsafeString); Console.WriteLine(safeJavaScript); // \u003Cscript\u003Ealert(\u0027XSS Attack!\u0027);\u003C/script\u003E string urlPart = "user input with spaces and & symbols"; // URL encode the string to safely include it in a URL. string encodedUrlPart = UrlEncoder.Default.Encode(urlPart); Console.WriteLine(encodedUrlPart); // user%20input%20with%20spaces%20and%20%26%20symbols ``` -------------------------------- ### Read Luau Buffer in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Shows how to execute Luau code that creates a buffer and then read its contents into a `LuauBuffer` in C#. The example further demonstrates how to convert the buffer's byte data into a readable string using `Encoding.UTF8.GetString`. ```C# var results = state.DoString("return buffer.fromstring('hello')"); var buffer = results[0].Read(); Console.WriteLine(Encoding.UTF8.GetString(buffer.AsSpan())); // hello ``` -------------------------------- ### Example of Generated Luau Type Definition File Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md This snippet shows the content of a Luau type definition file (`libs.d.luau`) generated by the `dluau` command. It declares a global `cmd` table with `foo` (number), `Hello` (function), and `echo` (function) members, providing type information for Luau code. ```lua -- libs.d.luau declare cmd: { foo: number, Hello: () -> (), echo: (value: string) -> (), } ``` -------------------------------- ### Initialize Low-Level JSON Reader/Writer with System.Text.Json Source: https://github.com/nuskey8/luau-dotnet/blob/main/src/Luau.Unity/Packages/nuget-packages/InstalledPackages/System.Text.Json.9.0.6/PACKAGE.md Demonstrates the initial setup for using `Utf8JsonWriter` for low-level JSON writing. This provides fine-grained control over JSON output, including formatting options like indentation. ```csharp using System; using System.IO; using System.Text; using System.Text.Json; var writerOptions = new JsonWriterOptions { Indented = true }; using var stream = new MemoryStream(); using var writer = new Utf8JsonWriter(stream, writerOptions); ``` -------------------------------- ### Create and Use Luau Buffer from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Illustrates how to create a `LuauBuffer` in C#, populate it with byte data using its `AsSpan()` method, and then assign it to a Luau global variable. The example concludes by showing how Luau code can convert this buffer back into a string. ```C# var buffer = state.CreateBuffer(10); var span = buffer.AsSpan(); span[0] = (byte)'1'; span[1] = (byte)'2'; span[2] = (byte)'3'; span[3] = (byte)'4'; span[4] = (byte)'5'; "hello"u8.CopyTo(span[5..]); state["b"] = buffer; var results = state.DoString("return buffer.tostring(b)"); Console.WriteLine(results[0]); // 12345hello ``` -------------------------------- ### Perform Low-Level Stack Operations with LuauState in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Provides an example of direct stack manipulation using `LuauState` in C#. It demonstrates pushing function references and arguments onto the stack, calling a function with specified argument and return counts, and retrieving the result from the stack. ```C# var bytecode = LuauCompiler.Compile( """ function add(a: number, b:number): number return a + b end """u8); state.Load(bytecode); // 引数のPush state.Push(state["add"]); state.Push(10); state.Push(20); // 関数の呼び出し state.Call(2, 1); // 結果をスタックから取得 var result = state.ToNumber(-1); state.Pop(1); ``` -------------------------------- ### Get LuauValue Type Property Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Illustrates how to execute a Luau script returning a string and then access the `Type` property of the `LuauValue` to determine its underlying Luau type, printing it to the console. ```cs var results = state.DoString("return 'hello'"); Console.WriteLine(results[0].Type); // string ``` -------------------------------- ### Exposing Synchronous C# Functions to Luau Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to expose a synchronous C# lambda expression as a Luau function using `state.CreateFunction()`. This allows Luau scripts to call C# methods directly, enabling interoperability. The example shows a simple addition function. ```C# state["add"] = state.CreateFunction((double a, double b) => { return a + b; }); // Execute on Luau side var results = state.DoString("return add(1, 2)"); Console.WriteLine(results[0]); // 3 ``` -------------------------------- ### Get Type of LuauValue Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Illustrates how to access the `Type` property of a `LuauValue` to determine its underlying Luau data type, such as 'string' for a string value. ```csharp var results = state.DoString("return 'hello'"); Console.WriteLine(results[0].Type); // string ``` -------------------------------- ### Execute Luau Script from C# using LuauState Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md This C# example illustrates the fundamental usage of `LuauState` to execute a Luau script string. It demonstrates how to initialize a Luau environment, run a simple script, and retrieve the returned values. It's important to note that `LuauState` is not thread-safe and should not be accessed concurrently from multiple threads. ```C# using Luau; using var state = LuauState.Create(); var results = state.DoString("return 1 + 1"); Console.WriteLine(results[0]); // 2 ``` -------------------------------- ### Using C# Async Iterators with IAsyncEnumerable Source: https://github.com/nuskey8/luau-dotnet/blob/main/src/Luau.Unity/Packages/nuget-packages/InstalledPackages/Microsoft.Bcl.AsyncInterfaces.9.0.6/PACKAGE.md This example demonstrates how to use C# async iterators (`IAsyncEnumerable`) to asynchronously yield a sequence of values. It shows a `Main` method consuming an `IAsyncEnumerable` using `await foreach` and a `GetValuesAsync` method that produces values with `yield return` after an asynchronous delay. ```C# using System; using System.Collections.Generic; using System.Threading.Tasks; internal static class Program { private static async Task Main() { Console.WriteLine("Starting..."); await foreach (var value in GetValuesAsync()) { Console.WriteLine(value); } Console.WriteLine("Finished!"); static async IAsyncEnumerable GetValuesAsync() { for (int i = 0; i < 10; i++) { await Task.Delay(TimeSpan.FromSeconds(1)); yield return i; } } } } ``` -------------------------------- ### Use Luau for .NET REPL Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md This snippet demonstrates how to launch the interactive Luau REPL using the `dotnet luau` command. Users can execute Luau code directly and see immediate results, similar to a standard console interpreter. ```ps1 $ dotnet luau > 1 + 2 3 ``` -------------------------------- ### Execute LuauAsset in Unity with LuauState Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Shows how to execute a `LuauAsset` (a `.luau` file treated as an asset in Unity) using `state.Execute()`. This allows precompiled Luau scripts to be run, reducing runtime overhead in Unity projects. ```C# using UnityEngine; using Luau; using Luau.Unity; public class Example : MonoBehaviour { [SerializeField] LuauAsset script; void Start() { using var state = LuauState.Create(); state.Execute(script); } } ``` -------------------------------- ### Use Luau.Native for Direct C API Bindings in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates a basic usage of the `Luau.Native` package to interact directly with the Luau C API. It shows how to create a new Luau state, push a number, retrieve it, and close the state. ```C# using Luau.Native; using static Luau.Native.NativeMethods; unsafe { lua_State* l = luaL_newstate(); lua_pushnumber(l, 12.3); double v = lua_tonumber(l, -1); lua_pop(l, 1); lua_close(l); } ``` -------------------------------- ### Use Luau for .NET CLI for REPL, Analysis, AST, and Compilation Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates the diverse functionalities of the `dotnet luau` CLI tool. This includes an interactive REPL, static analysis for type errors, abstract syntax tree (AST) generation, and bytecode compilation of Luau scripts. ```PowerShell $ dotnet luau > 1 + 2 3 ``` ```PowerShell $ dotnet luau analyze test.luau test.luau(1,1): TypeError: Type 'number' could not be converted into 'string' ``` ```PowerShell $ dotnet luau ast test.luau {"root":{"type":"AstStatBlock","location":"0,0 - 0,12","hasEnd":true,"body":[{"type":"AstStatReturn","location":"0,0 - 0,12","list":[{"type":"AstExprBinary","location":"0,7 - 0,12","op":"Add","left":{"type":"AstExprConstantNumber","location":"0,7 - 0,8","value":1},"right":{"type":"AstExprConstantNumber","location":"0,11 - 0,12","value":2}}]}]},"commentLocations":[]}% ``` ```PowerShell $ dotnet luau compile test.luau Function 0 (??): 1: return 1 + 2 LOADN R0 3 RETURN R0 1 ``` -------------------------------- ### Configure Luau Require Library with FileSystemLuauRequirer in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to initialize the Luau `require` library in C# using `FileSystemLuauRequirer` to customize module loading. It specifies the working directory and the path to the `.luaurc` configuration file for module resolution. ```C# state.OpenRequireLibrary(new FileSystemLuauRequirer { WorkingDirectory = "scripts/", // 基準となるディレクトリ ConfigFilePath = "scripts/.luaurc" // .luaurcのパス }); ``` -------------------------------- ### Execute LuauAsset in Unity with Luau for .NET Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Illustrates how to integrate Luau scripts into Unity projects using `LuauAsset`. This allows `.luau` files to be treated as assets, optionally pre-compiled, and executed directly by a `LuauState` instance within a MonoBehaviour. ```C# using UnityEngine; using Luau; using Luau.Unity; public class Example : MonoBehaviour { [SerializeField] LuauAsset script; void Start() { using var state = LuauState.Create(); state.Execute(script); } } ``` -------------------------------- ### Create and Use LuauTable from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Illustrates how to create a `LuauTable` instance directly from C#, populate it with values, assign it to a global variable in the Luau state, and then access its contents from a Luau script. ```cs LuauTable table = state.CreateTable(); table["a"] = "alpha"; state["t"] = table; var results = state.DoString("return t['a']"); Console.WriteLine(results[0]); // alpha ``` -------------------------------- ### Opening Individual Luau Standard Libraries in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how to selectively open specific Luau standard libraries (e.g., Base, Math, Table) within a `LuauState` instance using individual `Open~Library()` methods. This allows fine-grained control over the available Luau environment. ```C# using var state = LuauState.Create(); state.OpenBaseLibrary(); state.OpenMathLibrary(); state.OpenTableLibrary(); state.OpenStringLibrary(); state.OpenCoroutineLibrary(); state.OpenBit32Library(); state.OpenUtf8Library(); state.OpenOSLibrary(); state.OpenDebugLibrary(); state.OpenBufferLibrary(); state.OpenVectorLibrary(); ``` -------------------------------- ### Create and Use Luau Table from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Shows how to create a `LuauTable` instance directly in C#, populate it with values, and then assign it to a Luau global variable. This allows Luau code to access and manipulate the table created on the C# side. ```C# LuauTable table = state.CreateTable(); table["a"] = "alpha"; state["t"] = table; var results = state.DoString("return t['a']"); Console.WriteLine(results[0]); // alpha ``` -------------------------------- ### Read and Iterate LuauTable from Luau Script Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to execute a Luau script that returns a table, read it into a `LuauTable` object, access elements by key, and iterate through its key-value pairs using a `foreach` loop in C#. ```cs var results = state.DoString("return { a = 1, b = 2, c = 3 }"); var table = results[0].Read(); Console.WriteLine(table["a"]); // 1 foreach (KeyValuePair kv in table) { Console.WriteLine($"{kv.Key}:{kv.Value}"); } ``` -------------------------------- ### Configure Luau Requirers for Unity Resources and Addressables Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Explains how to enable Luau's `require` functionality for Unity's Resources and Addressables systems. It also demonstrates how to configure aliases for these requirers to customize module paths. ```C# state.OpenRequireLibrary(ResourcesLuauRequirer.Default); state.OpenRequireLibrary(AddressablesLuauRequirer.Default); ``` ```C# state.OpenRequireLibrary(new ResourcesLuauRequirer { Aliases = { ["Resources"] = "." } }); ``` -------------------------------- ### Configuring Luau `require()` with FileSystemLuauRequirer in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to configure Luau's `require()` mechanism in C# using `FileSystemLuauRequirer`. This allows Luau scripts to load modules from the file system, specifying a working directory and an optional `.luaurc` configuration file for path aliases. ```C# state.OpenRequireLibrary(new FileSystemLuauRequirer { WorkingDirectory = "scripts/", // Base directory ConfigFilePath = "scripts/.luaurc" // Path to .luaurc }); ``` ```APIDOC .luaurc Configuration Example: { "aliases": { "Script": "." } } Luau require() Usage with Alias: require "@Script/foo" ``` -------------------------------- ### Compile and Load Luau Bytecode in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Illustrates how to compile a Luau script string into bytecode using `LuauCompiler.Compile`. It then shows how to load the generated bytecode into a `LuauFunction` and invoke it to execute the script. ```C# byte[] bytecode = LuauCompiler.Compile("return 1 + 2"u8); ``` ```C# var func = state.Load(bytecode); var results = func.Invoke([]); Console.WriteLine(results[0]); // 3 ``` -------------------------------- ### Configure Unity Resources and Addressables Luau Requirers in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Explains how to integrate Unity's `Resources` and `Addressables` systems with the Luau `require` library using `ResourcesLuauRequirer` and `AddressablesLuauRequirer`. It also demonstrates how to pass aliases explicitly for these requirers. ```C# state.OpenRequireLibrary(ResourcesLuauRequirer.Default); state.OpenRequireLibrary(AddressablesLuauRequirer.Default); ``` ```C# state.OpenRequireLibrary(new ResourcesLuauRequirer { Aliases = { ["Resources"] = "." } }); ``` -------------------------------- ### Execute Luau Script in C# with LuauState Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to create a `LuauState` instance, execute a Luau script string, and retrieve the results in C#. It's important to note that `LuauState` is not thread-safe. ```csharp using Luau; using var state = LuauState.Create(); var results = state.DoString("return 1 + 1"); Console.WriteLine(results[0]); // 2 ``` -------------------------------- ### Configure Luau for Unity in manifest.json Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md This JSON snippet demonstrates how to manually add the Luau.Unity package as a dependency in your Unity project's `Packages/manifest.json` file. It specifies the package identifier and the Git URL for retrieval, providing an alternative to the Package Manager UI. ```JSON { "dependencies": { "com.nuskey.luau.unity": "https://github.com/nuskey8/luau-dotnet.git?path=src/Luau.Unity/Assets/Luau.Unity" } } ``` -------------------------------- ### Open Specific Luau Standard Libraries Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Illustrates how to selectively enable individual Luau standard libraries (e.g., Base, Math, Table, String, Coroutine, Bit32, Utf8, OS, Debug, Buffer, Vector) by calling their respective `Open` methods on the `LuauState` instance. This provides fine-grained control over available Luau functionalities. ```C# using var state = LuauState.Create(); state.OpenBaseLibrary(); state.OpenMathLibrary(); state.OpenTableLibrary(); state.OpenStringLibrary(); state.OpenCoroutineLibrary(); state.OpenBit32Library(); state.OpenUtf8Library(); state.OpenOSLibrary(); state.OpenDebugLibrary(); state.OpenBufferLibrary(); state.OpenVectorLibrary(); ``` -------------------------------- ### Create LuauUserData from C# Struct Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how to create `LuauUserData` from a C# unmanaged struct using `state.CreateUserData()`, demonstrating the definition of the struct and its instantiation for Luau interoperability. ```cs LuauUserData userdata = state.CreateUserData(new() { Foo = 5, Bar = 1.5, }); struct Example { public int Foo; public double Bar; } ``` -------------------------------- ### Create and Populate LuauBuffer from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how to create a `LuauBuffer` from C# with a specified size, populate its underlying span with byte data, assign it to a global Luau variable, and then convert it back to a string from within a Luau script. ```cs var buffer = state.CreateBuffer(10); var span = buffer.AsSpan(); span[0] = (byte)'1'; span[1] = (byte)'2'; span[2] = (byte)'3'; span[3] = (byte)'4'; span[4] = (byte)'5'; "hello"u8.CopyTo(span[5..]); state["b"] = buffer; var results = state.DoString("return buffer.tostring(b)"); Console.WriteLine(results[0]); // 12345hello ``` -------------------------------- ### Opening Custom Luau Libraries in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how to register a custom C# library, defined with `[LuauLibrary]`, into a `LuauState` instance using `OpenLibrary()`. Once opened, the library's members become accessible from Luau scripts under the specified library name. ```C# state.OpenLibrary(); ``` -------------------------------- ### Compile Luau Code to Bytecode with CLI Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md This command compiles a Luau source file into Luau bytecode, displaying the generated instructions. It provides insight into the low-level execution plan of the Luau virtual machine, useful for performance analysis or debugging compilation issues. ```ps1 $ dotnet luau compile test.luau Function 0 (??): 1: return 1 + 2 LOADN R0 3 RETURN R0 1 ``` -------------------------------- ### Read LuauValue as C# double Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to execute a Luau script that returns a number and then read the resulting `LuauValue` into a C# `double` using the `Read()` method. ```cs var results = state.DoString("return 1 + 1"); // double var value = results[0].Read(); ``` -------------------------------- ### Execute Luau Scripts Synchronously and Asynchronously Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Compares the synchronous `DoString()` and asynchronous `DoStringAsync()` methods of `LuauState` for executing Luau scripts, highlighting their usage and the importance of `DoStringAsync()` for scripts containing C# asynchronous functions. ```cs using var state = LuauState.Create(); // sync state.DoString("foo()"); // async await state.DoStringAsync("foo()"); ``` -------------------------------- ### Defining Custom Luau Libraries using C# [LuauLibrary] Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Explains how to create custom Luau libraries in C# using the `[LuauLibrary]` attribute. This allows exposing C# fields, properties, and static or instance methods to Luau, enabling complex interoperability and extending Luau's capabilities with C# logic. ```C# // The partial keyword is required because Source Generator generates necessary code [LuauLibrary("foo")] partial class FooLibrary { [LuauMember] public double field = 10; [LuauMember("property")] public double Property { get; set; } = 20; [LuauMember("hello")] public static void Hello() { Console.WriteLine("hello!"); } [LuauMember("echo")] public static void Echo(string value) { Console.WriteLine(value); } [LuauMember("getfield")] public double GetField() { return field; } } ``` -------------------------------- ### Read Luau Table in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to execute Luau code that returns a table and then read its contents in C# using `LuauTable`. This includes accessing elements by key and iterating through key-value pairs to process table data. ```C# var results = state.DoString("return { a = 1, b = 2, c = 3 }"); var table = results[0].Read(); Console.WriteLine(table["a"]); // 1 foreach (KeyValuePair kv in table) { Console.WriteLine($"{kv.Key}:{kv.Value}"); } ``` -------------------------------- ### Add Luau for Unity via Git URL in Package Manager Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md This URL is used within Unity's Package Manager to directly add the Luau.Unity package from its GitHub repository. It allows developers to integrate the library into their Unity projects without relying on a pre-published Unity package. ```Text https://github.com/nuskey8/luau-dotnet.git?path=src/Luau.Unity/Assets/Luau.Unity ``` -------------------------------- ### Related NuGet Packages for System.Text.Json Source: https://github.com/nuskey8/luau-dotnet/blob/main/src/Luau.Unity/Packages/nuget-packages/InstalledPackages/System.Text.Json.9.0.6/PACKAGE.md Lists additional NuGet packages that complement or extend the functionality of System.Text.Json for specific data handling and HTTP scenarios, providing abstractions and serialization capabilities beyond the core library. ```APIDOC System.Memory.Data: Lightweight data formats abstraction System.Net.Http.Json: Serialization of HttpContent ``` -------------------------------- ### Accessing Custom C# Libraries from Luau Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to interact with a custom library (defined in C#) from a Luau script. It shows accessing fields, properties, and calling methods exposed by the C# library, illustrating the seamless integration. ```Luau print(foo.field) -- 10 print(foo.property) -- 20 foo.field = 50 foo.hello() -- hello! foo.echo("foo") -- foo print(foo.getfield()) -- 50 ``` -------------------------------- ### Generate Luau Abstract Syntax Tree (AST) with CLI Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md This command outputs the Abstract Syntax Tree (AST) of a given Luau file in JSON format. The AST represents the syntactic structure of the code, useful for advanced analysis, tooling, or understanding parsing results. ```ps1 $ dotnet luau ast test.luau {"root":{"type":"AstStatBlock","location":"0,0 - 0,12","hasEnd":true,"body":[{"type":"AstStatReturn","location":"0,0 - 0,12","list":[{"type":"AstExprBinary","location":"0,7 - 0,12","op":"Add","left":{"type":"AstExprConstantNumber","location":"0,7 - 0,8","value":1},"right":{"type":"AstExprConstantNumber","location":"0,11 - 0,12","value":2}}]}]},"commentLocations":[]}% ``` -------------------------------- ### Invoke Luau Function from C# using LuauFunction Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to load a Luau script containing a function, retrieve the function as a `LuauFunction` object, and then asynchronously invoke it from C# with arguments, printing the returned result. ```lua -- sample.luau local function add(a: number, b: number): number return a + b end return add ``` ```cs using var state = LuauState.Create(); var bytes = await File.ReadAllBytes("sample.luau"); var func = state.DoString(bytes)[0] .Read(); // Execute with arguments var results = await func.InvokeAsync([1, 2]); Console.WriteLine(results[0]); // 3 ``` -------------------------------- ### Control Luau Coroutine from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to create a Luau coroutine, retrieve it as a `LuaState` object in C#, and then control its execution step-by-step using `co.Resume(state)`. This allows C# to manage the lifecycle and yield points of Luau coroutines. ```Luau local co = coroutine.create(function() for i = 1, 10 do print(i) coroutine.yield() end end) return co ``` ```C# var bytes = File.ReadAllBytes("coroutine.luau"); var results = state.DoString(bytes); var co = results[0].Read(); for (int i = 0; i < 10; i++) { var resumeResults = co.Resume(state); // coroutine.resume()と同様、成功時は最初の要素にtrue、それ以降に関数の戻り値を返す // 1, 2, 3, 4, ... Console.WriteLine(resumeResults[1]); } ``` -------------------------------- ### Read LuauBuffer from Luau Script Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Illustrates how to execute a Luau script that creates a buffer from a string, then read the resulting `LuauBuffer` into C# and convert its contents back to a string using `Encoding.UTF8.GetString`. ```cs var results = state.DoString("return buffer.fromstring('hello')"); var buffer = results[0].Read(); Console.WriteLine(Encoding.UTF8.GetString(buffer.AsSpan())); // hello ``` -------------------------------- ### Add Luau Unity Package to manifest.json Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Manually adds the Luau Unity package as a dependency by editing the project's 'Packages/manifest.json' file. This provides an alternative to the Git URL method. ```json { "dependencies": { "com.nuskey.luau.unity": "https://github.com/nuskey8/luau-dotnet.git?path=src/Luau.Unity/Assets/Luau.Unity" } } ``` -------------------------------- ### Expose Synchronous C# Function to Luau Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to create a synchronous C# function using `state.CreateFunction()` with a lambda expression and expose it to Luau. This allows Luau code to call C# methods as if they were native Luau functions. ```C# state["add"] = state.CreateFunction((double a, double b) => { return a + b; }); // Luau側で実行 var results = state.DoString("return add(1, 2)"); Console.WriteLine(results[0]); // 3 ``` -------------------------------- ### Creating and Executing Luau Threads from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Explains how to create independent Luau threads (`LuauState`) that share the global environment using `state.CreateThread()`. This is useful for running multiple Luau scripts concurrently without interference. ```C# var thread = state.CreateThread(); thread.DoString("return 1 + 2"); ``` -------------------------------- ### Compile Luau Script to Bytecode in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to compile a Luau script string into bytecode using the `LuauCompiler.Compile()` method. This is useful for pre-compiling Luau files to improve runtime performance. ```C# byte[] bytecode = LuauCompiler.Compile("return 1 + 2"u8); ``` -------------------------------- ### Implicit Conversion to LuauValue in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates the implicit conversion capabilities from common C# types like `double`, `string`, and `LuauTable` to `LuauValue`, simplifying value assignment. ```csharp LuauValue value; value = 1.2; // double -> LuauValue value = "foo"; // string -> LuauValue value = state.CreateTable(); // LuaTable -> LuauValue ``` -------------------------------- ### Load and Invoke Compiled Luau Bytecode in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how to load previously compiled Luau bytecode into a `LuauFunction` object using `state.Load()`. The function can then be invoked, and its results retrieved from the Luau state. ```C# var func = state.Load(bytecode); var results = func.Invoke([]); Console.WriteLine(results[0]); // 3 ``` -------------------------------- ### Perform Low-Level Stack Operations with LuauState in C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Illustrates how to directly manipulate the Luau stack using `LuauState` for advanced scenarios. This includes pushing functions and arguments, calling functions, and retrieving results from the stack. ```C# var bytecode = LuauCompiler.Compile( """ function add(a: number, b:number): number return a + b end """u8); state.Load(bytecode); // Push arguments state.Push(state["add"]); state.Push(10); state.Push(20); // Call function state.Call(2, 1); // Get result from stack var result = state.ToNumber(-1); state.Pop(1); ``` -------------------------------- ### Generate Luau Type Definition File from C# Library Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to use the `dotnet luau dluau` command to generate a Luau type definition file (`.d.luau`) from a C# project. This process leverages the `[LuauLibrary]` attributes defined in the C# source. ```PowerShell $ dotnet luau dluau Program.cs -o libs.d.luau ``` -------------------------------- ### Serialize and Deserialize Objects with System.Text.Json Source: https://github.com/nuskey8/luau-dotnet/blob/main/src/Luau.Unity/Packages/nuget-packages/InstalledPackages/System.Text.Json.9.0.6/PACKAGE.md Demonstrates basic object serialization to JSON and deserialization back to an object using `JsonSerializer.Serialize` and `JsonSerializer.Deserialize`. This approach uses reflection for type mapping. ```csharp using System; using System.Text.Json; WeatherForecast forecast = new (DateTimeOffset.Now, 26.6f, "Sunny"); var serialized = JsonSerializer.Serialize(forecast); Console.WriteLine(serialized); // {"Date":"2023-08-02T16:01:20.9025406+00:00","TemperatureCelsius":26.6,"Summary":"Sunny"} var forecastDeserialized = JsonSerializer.Deserialize(serialized); Console.WriteLine(forecast == forecastDeserialized); // True public record WeatherForecast(DateTimeOffset Date, float TemperatureCelsius, string? Summary); ``` -------------------------------- ### Luau-dotnet Type Mapping: Luau to C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Provides a comprehensive mapping of Luau value types to their corresponding C# representations within the Luau-dotnet library, detailing how different Luau data types are handled in C#. ```APIDOC Luau: nil -> C#: LuaValue.Nil Luau: boolean -> C#: bool Luau: lightuserdata -> C#: IntPtr Luau: number -> C#: double, float Luau: vector -> C#: System.Numerics.Vector3 Luau: string -> C#: string Luau: table -> C#: LuauTable Luau: function -> C#: LuauFunction Luau: userdata -> C#: T, LuauUserData Luau: thread -> C#: LuauState Luau: buffer -> C#: LuauBuffer ``` -------------------------------- ### Access Luau Global Variables from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Demonstrates how to set a global variable in the Luau state from C# using the `LuauState` indexer, and then retrieve and print its value by executing a Luau script that accesses the same global variable. ```cs state["a"] = 10; var results = state.DoString("return a"); Console.WriteLine(results[0]); ``` -------------------------------- ### Define Luau Library in C# for Type Generation Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md This C# code defines a `partial class` annotated with `[LuauLibrary]`, exposing members (`foo`, `Hello`, `Echo`) that can be reflected into Luau type definitions. This mechanism allows C# code to be seamlessly integrated and type-checked within Luau projects. ```cs [LuauLibrary("cmd")] partial class Commands { [LuauMember] public double foo; [LuauMember] public void Hello() { Console.WriteLine("Hello!"); } [LuauMember("echo")] public static void Echo(string value) { Console.WriteLine(value); } } ``` -------------------------------- ### Create Luau Thread for Independent Execution Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Explains how to create a new Luau thread using `state.CreateThread()`. This thread shares the global environment with the main state but allows for independent script execution, which is useful for parallelizing tasks or managing separate script contexts. ```C# var thread = state.CreateThread(); thread.DoString("return 1 + 2"); ``` -------------------------------- ### Invoke Luau Function from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Shows how to load a Luau function from a file, read it into a `LuauFunction` object in C#, and then invoke it asynchronously with arguments using `InvokeAsync`. This enables C# applications to call functions defined within Luau scripts. ```Luau local function add(a: number, b: number): number return a + b end return add ``` ```C# using var state = LuauState.Create(); var bytes = await File.ReadAllBytes("sample.luau"); var func = state.DoString(bytes)[0] .Read(); // 引数を与えて実行 var results = await func.InvokeAsync([1, 2]); Console.WriteLine(results[0]); // 3 ``` -------------------------------- ### Use Aliased Paths for Module Requiring in Luau Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Illustrates how to use a previously defined alias (e.g., `@Script`) within a Luau `require` statement to load modules from an aliased path, improving readability and organization. ```Lua require "@Script/foo" ``` -------------------------------- ### Implicitly Convert C# Types to LuauValue Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how various C# primitive types (double, string) and `LuauTable` instances are implicitly converted to `LuauValue` when assigned, simplifying value creation from the C# side. ```cs LuauValue value; value = 1.2; // double -> LuauValue value = "foo"; // string -> LuauValue value = state.CreateTable(); // LuaTable -> LuauValue ``` -------------------------------- ### Define Luau Library with C# Attributes for Type Generation Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Shows how to define a C# class using `[LuauLibrary]` and `[LuauMember]` attributes. These attributes allow .NET methods and fields to be exposed to Luau, facilitating the automatic generation of Luau type definition files. ```C# [LuauLibrary("cmd")] partial class Commands { [LuauMember] public double foo; [LuauMember] public void Hello() { Console.WriteLine("Hello!"); } [LuauMember("echo")] public static void Echo(string value) { Console.WriteLine(value); } } ``` -------------------------------- ### Consume Custom C# Libraries in Luau Scripts Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to interact with a custom Luau library defined in C# from within a Luau script. It shows accessing fields and properties, modifying values, and calling methods exposed by the C# library. ```Lua print(foo.field) -- 10 print(foo.property) -- 20 foo.field = 50 foo.hello() -- hello! foo.echo("foo") -- foo print(foo.getfield()) -- 50 ``` -------------------------------- ### Expose Asynchronous C# Function to Luau Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Illustrates how to create an asynchronous C# function using `state.CreateFunction()` with an `async` lambda expression, making it callable from Luau. When Luau calls such a function, the execution requires using the asynchronous Luau API. ```C# state["wait"] = state.CreateFunction(async (double seconds, CancellationToken ct) => { await Task.Delay(TimeSpan.FromSeconds(seconds), ct); }); await state.DoStringAsync("wait(1)"); // 1秒待機する ``` -------------------------------- ### Access Luau Global Variables from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README_JA.md Demonstrates how to read and write Luau global variables directly from C# using the `LuauState` indexer. This allows for seamless data exchange, where C# sets a global variable and Luau code retrieves its value. ```C# state["a"] = 10; var results = state.DoString("return a"); Console.WriteLine(results[0]); ``` -------------------------------- ### Serialize and Deserialize Objects using System.Text.Json Source Generators Source: https://github.com/nuskey8/luau-dotnet/blob/main/src/Luau.Unity/Packages/nuget-packages/InstalledPackages/System.Text.Json.9.0.6/PACKAGE.md Illustrates how to use `System.Text.Json` source generators for improved performance during serialization and deserialization. This method requires defining a `JsonSourceGenerationOptions` and `JsonSerializable` context. ```csharp using System.Text.Json; using System.Text.Json.Serialization; WeatherForecast forecast = new (DateTimeOffset.Now, 26.6f, "Sunny"); var serialized = JsonSerializer.Serialize(forecast, SourceGenerationContext.Default.WeatherForecast); Console.WriteLine(serialized); // {"Date":"2023-08-02T16:01:20.9025406+00:00","TemperatureCelsius":26.6,"Summary":"Sunny"} var forecastDeserialized = JsonSerializer.Deserialize(serialized, SourceGenerationContext.Default.WeatherForecast); Console.WriteLine(forecast == forecastDeserialized); // True public record WeatherForecast(DateTimeOffset Date, float TemperatureCelsius, string? Summary); [JsonSourceGenerationOptions(WriteIndented = true)] [JsonSerializable(typeof(WeatherForecast))] internal partial class SourceGenerationContext : JsonSerializerContext { } ``` -------------------------------- ### Managing Luau Coroutines from C# Source: https://github.com/nuskey8/luau-dotnet/blob/main/README.md Details how to create and manage Luau coroutines from the C# side. A Luau script defines a coroutine, which is then loaded into C# as a `LuaState` object. C# can then `Resume` the coroutine iteratively, processing its yielded values. ```Luau -- coroutine.luau local co = coroutine.create(function() for i = 1, 10 do print(i) coroutine.yield() end end) return co ``` ```C# var bytes = File.ReadAllBytes("coroutine.luau"); var results = state.DoString(bytes); var co = results[0].Read(); for (int i = 0; i < 10; i++) { var resumeResults = co.Resume(state); // Similar to coroutine.resume(), returns true in the first element on success, followed by function return values // 1, 2, 3, 4, ... Console.WriteLine(resumeResults[1]); } ```