Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,7 @@ 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.
See the [standard library API reference](docs/stdlib/README.md) for each function's inputs/results, official Lua 5.2 links, and implementation differences with their reasons. It also lists unavailable APIs and current limitations. The [Lua official manual](https://www.lua.org/manual/5.2/manual.html#6) defines the full language/library contract.

## Functions

Expand Down
5 changes: 1 addition & 4 deletions README_JA.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,7 @@ var results = await state.DoStringAsync("return math.pi");
Console.WriteLine(results[0]); // 3.141592653589793
```

標準ライブラリについては[Lua公式のマニュアル](https://www.lua.org/manual/5.2/manual.html#6)を参照してください。

> [!WARNING]
> Lua-CSharpは標準ライブラリの全ての関数をサポートしているわけではありません。詳細は[互換性](#互換性)の項目を参照してください。
各APIの引数・戻り値、Lua 5.2公式リファレンスへのリンク、実装上の違いと理由は[標準ライブラリAPIリファレンス(英語)](docs/stdlib/README.md)を参照してください。未対応APIと現在の制限も記載しています。言語・ライブラリの完全な仕様は[Lua公式のマニュアル](https://www.lua.org/manual/5.2/manual.html#6)を参照してください。

## 関数

Expand Down
78 changes: 78 additions & 0 deletions docs/stdlib/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Lua standard library reference

This reference describes the Lua-facing APIs installed by Lua-CSharp. Each API links to its entry in the [official Lua 5.2 manual](https://www.lua.org/manual/5.2/manual.html#6). The manual defines the Lua contract; these pages explain the managed implementation, available configuration, and known limitations. Comparisons with C Lua use the [official Lua 5.2.4 source](https://www.lua.org/source/5.2/), with platform/build differences called out where relevant.

## Open libraries

```csharp
using Lua;
using Lua.Platforms;
using Lua.Standard;

using var state = LuaState.Create();
state.OpenStandardLibraries();

// For Lua byte strings and raw stream contents:
using var bytes = LuaState.Create(LuaPlatform.DefaultByteStrings with
{
NumberFormat = LuaNumberFormat.Lua,
});
bytes.OpenStandardLibraries();
```

Libraries are opt-in. `LuaState.Create()` alone does not install them. To install a subset, call the corresponding extension in the table below. Configure standard I/O before opening its library: changing the provider later does not replace existing handles. Existing module closures also retain their captured package table.

Opening a library again republishes its globals/table; it is not an ensure-loaded operation. For example, reopening math replaces its random generator, and reopening I/O resets the default handles.

| Reference | C# initialization | Official library/global |
| --- | --- | --- |
| [Basic functions and globals](basic.md) | `OpenBasicLibrary()` | [Basic library](https://www.lua.org/manual/5.2/manual.html#6.1) |
| [Coroutines](coroutine.md) | `OpenCoroutineLibrary()` | [`coroutine`](https://www.lua.org/manual/5.2/manual.html#pdf-coroutine) |
| [Packages and modules](package.md) | `OpenModuleLibrary()` | [`package`](https://www.lua.org/manual/5.2/manual.html#pdf-package) |
| [Strings](string.md) | `OpenStringLibrary()` | [`string`](https://www.lua.org/manual/5.2/manual.html#pdf-string) |
| [Tables](table.md) | `OpenTableLibrary()` | [`table`](https://www.lua.org/manual/5.2/manual.html#pdf-table) |
| [Mathematics](math.md) | `OpenMathLibrary()` | [`math`](https://www.lua.org/manual/5.2/manual.html#pdf-math) |
| [Bitwise operations](bit32.md) | `OpenBitwiseLibrary()` | [`bit32`](https://www.lua.org/manual/5.2/manual.html#pdf-bit32) |
| [Files and standard I/O](io.md) | `OpenIOLibrary()` | [`io`](https://www.lua.org/manual/5.2/manual.html#pdf-io) |
| [Operating system](os.md) | `OpenOperatingSystemLibrary()` | [`os`](https://www.lua.org/manual/5.2/manual.html#pdf-os) |
| [Debugging](debug.md) | `OpenDebugLibrary()` | [`debug`](https://www.lua.org/manual/5.2/manual.html#pdf-debug) |

## Reading the API tables

Signatures use `[optional]` arguments and `...` for multiple values. The last column includes both implementation details and compatibility differences; a managed backend alone does not imply different Lua behavior. A blank notes cell means no additional note is documented for that API; the shared behavior below still applies. These are implementation notes, not a guarantee that every edge case matches every C Lua build.

Notes marked **Limitation** describe incomplete compatibility, not a recommended Lua idiom. Notes marked **Host-dependent** depend on a replaceable provider. Explanations identify the implementation mechanism; they do not imply that an existing limitation is intentional.

## Shared behavior

### Strings and positions

The default `LuaStringMode.Utf16` uses .NET UTF-16 code units. `LuaStringMode.Bytes` stores one byte per C# `char`, matching Lua 5.2's byte-string representation. This affects lengths, slices, pattern positions, character classes, and stream counts. Neither mode counts grapheme clusters. See [String modes](../string-modes.md) for conversions and stream configuration.

This difference allows ordinary C# strings to be used directly in the default mode. Choose byte mode for Lua scripts that depend on byte positions or binary file contents. The `b` in `io.open` does not select the state's string mode.

### Numbers and text

Lua numbers use .NET `double`. `LuaPlatform.NumberFormat` defaults to `DotNet`, using invariant .NET numeric text. `Lua` selects 14 significant digits for implicit conversions and portable signed `inf`/`nan` spellings. This is a formatting policy; it does not change arithmetic or parsing.

This setting affects numeric `tostring`, `print`, numeric I/O, `table.concat`, `gsub` replacements, and applicable `string.format` conversions. A particular C runtime may spell special values differently, including Windows `nan(ind)` or `nan(snan)`; the `Lua` policy deliberately uses portable spellings. See [number formatting](../../README.md#number-formatting).

### Async calls, cancellation, and errors

C# functions and platform providers can await asynchronous work. Lua execution awaits them; an incomplete `Task` is not a Lua `coroutine.yield`. Lua callbacks entered through non-yieldable library operations, such as a sort comparator or a `gsub` replacement, cannot yield across that boundary. This preserves Lua 5.2 behavior while allowing C# async integration.

Host execution cancellation propagates to C# rather than becoming a normal `pcall` result. Built-in stream reads check cancellation at entry and before buffer fills; cancellation cannot interrupt an already blocking synchronous `Stream.Read`. Error wording and tracebacks can contain .NET exception messages and C# frames.

### Memory and host objects

The .NET garbage collector owns object lifetimes. Lua weak-table `__mode` semantics and Lua `__gc` finalizers are not implemented; .NET collection does not supply these Lua protocols. Lua GC tuning is also unavailable, and `collectgarbage` has significant limitations documented in [Basic functions](basic.md). Close files explicitly when their close timing matters.

C# objects can be exposed as userdata, and host functions are wrapped as `LuaFunction` values. Their identity strings and debug metadata describe managed objects rather than native pointers. Host-frozen tables, including generated C# metatables, reject mutation even through raw table operations; this keeps their published interop definitions immutable.

Host userdata implementing `ILuaUserData` has a per-object metatable. Light-userdata object tokens, including `debug.upvalueid` results, instead share one type metatable within a global state and its coroutines, as in Lua 5.2. `debug.setmetatable` can replace or remove that shared metatable; independent states have separate metatables.

## Scope

The pages include missing APIs from Lua 5.2, not just registered functions. Legacy Lua 5.1 compatibility aliases and later-version additions are listed separately where useful. This reference covers Lua script APIs; it does not replace the C# API documentation.

Implementation entry point: [OpenLibsExtensions.cs](../../src/Lua/Standard/OpenLibsExtensions.cs).
36 changes: 36 additions & 0 deletions docs/stdlib/basic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Basic functions and globals

[Reference index](README.md) · [Official Lua 5.2 basic library](https://www.lua.org/manual/5.2/manual.html#6.1) · [C Lua 5.2.4 source](https://www.lua.org/source/5.2/lbaselib.c.html) · [Implementation](../../src/Lua/Standard/BasicLibrary.cs)

Install with `state.OpenBasicLibrary()`. Functions are globals. The [shared string, numeric-text, cancellation, and host-object behavior](README.md#shared-behavior) applies throughout.

| API / official reference | Inputs and result | Lua-CSharp implementation notes and differences |
| --- | --- | --- |
| [`assert(v [, message])`](https://www.lua.org/manual/5.2/manual.html#pdf-assert) | Returns all arguments when `v` is truthy; otherwise raises an assertion error. The default message is `assertion failed!`. | The host receives a `LuaAssertionException`. Lua 5.2's message is string-like: a number is converted to text; an arbitrary table is not an assertion error object. |
| [`collectgarbage([opt [, arg]])`](https://www.lua.org/manual/5.2/manual.html#pdf-collectgarbage) | Recognizes `collect`, `stop`, `restart`, `count`, `step`, `setpause`, `setstepmul`, `setmajorinc`, `isrunning`, `incremental`, and `generational`. | **Limitation:** every recognized option calls `GC.Collect()` and returns **no values**. `arg` is ignored. Thus `count` does not report memory, `stop` does not stop GC, and tuning/mode options do not tune it. The implementation delegates to .NET GC without implementing Lua's collector control protocol. |
| [`dofile([filename])`](https://www.lua.org/manual/5.2/manual.html#pdf-dofile) | Loads and executes a file, or standard input for an omitted/nil filename; returns its results and raises load/runtime failures. | Files use `LuaPlatform.FileSystem`; standard input uses `LuaPlatform.StandardIO.Input` and remains open. Paths are decoded to .NET text in byte mode. |
| [`error(message [, level])`](https://www.lua.org/manual/5.2/manual.html#pdf-error) | Raises the supplied error object. At positive levels, numbers become strings and string messages receive a source prefix when that level exists. At level 0 or below, the original object is preserved. | Host-facing errors use `LuaRuntimeException`; stack descriptions include managed frames. Numeric text follows `NumberFormat`. |
| [`_G`](https://www.lua.org/manual/5.2/manual.html#pdf-_G) | The initial global environment table. | Installed from the state's managed environment. Assigning `_G` does not rewrite a function's `_ENV`. |
| [`getmetatable(value)`](https://www.lua.org/manual/5.2/manual.html#pdf-getmetatable) | Returns the metatable, its protected `__metatable` value, or nil. | Also works with managed userdata. |
| [`ipairs(t)`](https://www.lua.org/manual/5.2/manual.html#pdf-ipairs) | Uses `__ipairs` when present; otherwise returns an iterator, the table, and `0`, stopping at the first missing integer element. The default iterator converts its control value to an integer and returns one nil at exhaustion, as in Lua 5.2. | `__ipairs` cannot yield across the library callback boundary. |
| [`load(ld [, source [, mode [, env]]])`](https://www.lua.org/manual/5.2/manual.html#pdf-load) | Compiles source/bytecode from a string or a reader function. Returns a function, or `nil, error`; an empty reader result ends input. `mode` defaults to `bt`. Explicit `env`, including nil, initializes the first upvalue. | **Limitation:** reader pieces are collected before parsing, so readers can be called past the point where C Lua would detect a syntax error or finish a binary chunk. This follows the current whole-input compiler interface. Reader callbacks cannot Lua-yield, but C# readers can await. Raw binary strings work in either mode; see [dumping](string.md#dumping-and-loading). |
| [`loadfile([filename [, mode [, env]]])`](https://www.lua.org/manual/5.2/manual.html#pdf-loadfile) | Compiles a file, or standard input for an omitted/nil filename; returns a function or `nil, error`. Recognizes an initial UTF-8 BOM and first-line `#` comment. | Uses the configured filesystem, with byte-mode paths decoded to .NET text. Standard input uses `LuaPlatform.StandardIO.Input`, independently of `io.input`/`io.stdin` assignments, has chunk name `=stdin`, and remains open on success or failure. Mode/environment handling is the same for both sources; bytecode requires an input provider exposing raw bytes through `ILuaByteStream`, as the default console provider does. |
| [`next(t [, index])`](https://www.lua.org/manual/5.2/manual.html#pdf-next) | Returns the next key/value, or nil after the last key. Omitted/nil `index` starts traversal. | Order follows the managed table storage and is unspecified. **Limitation:** an unknown hash key such as `next({}, 'missing')` returns nil instead of C Lua's invalid-key error: the managed lookup treats that missing iteration position as the end. |
| [`pairs(t)`](https://www.lua.org/manual/5.2/manual.html#pdf-pairs) | Uses `__pairs`, or returns the default iterator, table, and nil. | `__pairs` cannot Lua-yield across the library callback boundary. |
| [`pcall(f [, ...])`](https://www.lua.org/manual/5.2/manual.html#pdf-pcall) | Returns `true, ...results`, or `false, errorObject`. Callable values with `__call` are supported. | Host execution cancellation escapes to C# rather than being consumed as a script error. |
| [`print(...)`](https://www.lua.org/manual/5.2/manual.html#pdf-print) | Calls the global `tostring` for each argument and writes tab-separated output plus a newline. | **Host-dependent:** writes to `LuaPlatform.StandardIO.Output`, which may be a console, redirected stream, or Unity logger. As in C Lua, selecting `io.output` does not redirect `print`. Numeric text uses `NumberFormat`; the `tostring` callbacks cannot Lua-yield. |
| [`rawequal(a, b)`](https://www.lua.org/manual/5.2/manual.html#pdf-rawequal) | Compares values without `__eq`; strings compare by contents. | Tables, functions, threads, and userdata use managed object identity, corresponding to Lua's identity comparison for these types. |
| [`rawget(t, key)`](https://www.lua.org/manual/5.2/manual.html#pdf-rawget) | Reads a table slot without `__index`. | |
| [`rawlen(v)`](https://www.lua.org/manual/5.2/manual.html#pdf-rawlen) | Returns the raw table length or string length without `__len`. | String length counts UTF-16 code units in default mode and bytes in byte mode. |
| [`rawset(t, key, value)`](https://www.lua.org/manual/5.2/manual.html#pdf-rawset) | Writes without `__newindex` and returns `t`. | Host-frozen tables still reject writes; raw access bypasses metamethods, not the managed table's read-only state. |
| [`select(index, ...)`](https://www.lua.org/manual/5.2/manual.html#pdf-select) | `"#"` returns the argument count. A numeric index selects a suffix; negative indices count from the end. | |
| [`setmetatable(t, mt)`](https://www.lua.org/manual/5.2/manual.html#pdf-setmetatable) | Assigns a table metatable or removes it with nil; returns `t`. Protected metatables cannot be changed. | Host-frozen tables also prevent replacing their metatable. |
| [`tonumber(v [, base])`](https://www.lua.org/manual/5.2/manual.html#pdf-tonumber) | Parses numeric text or returns nil. With an explicit base, accepts bases 2–36 and a signed integer string. | A numeric `v` with an explicit base is first formatted using `NumberFormat`, which can affect parsing. Explicit-base digits accumulate in a double, as in the default C Lua 5.2 implementation; no newer Lua integer-subtype arithmetic is used. |
| [`tostring(v)`](https://www.lua.org/manual/5.2/manual.html#pdf-tostring) | Uses `__tostring` when present; otherwise produces the value's standard text. | Numeric output uses `NumberFormat`; managed identities replace C pointer-like representations. `__tostring` cannot Lua-yield through this callback. |
| [`type(v)`](https://www.lua.org/manual/5.2/manual.html#pdf-type) | Reports a Lua type name, including `userdata` for host objects and `thread` for Lua states. | C# functions are reported as `function`; .NET types are not exposed as separate Lua type names. |
| [`_VERSION`](https://www.lua.org/manual/5.2/manual.html#pdf-_VERSION) | The string `"Lua 5.2"`. | Reports the language target, not the Lua-CSharp NuGet/package version. |
| [`xpcall(f, msgh [, ...])`](https://www.lua.org/manual/5.2/manual.html#pdf-xpcall) | Calls `f` protected; on failure invokes `msgh(error)` before unwinding and returns `false, handledError`. On success returns `true, ...results`. | A handler failure produces `error in error handling`. The implementation terminates handler failure directly instead of repeatedly re-entering the same handler. Host execution cancellation propagates to C#. |

## Compatibility names

Lua-CSharp does not install the deprecated Lua 5.1 names `loadstring`, global `unpack`, `getfenv`, `setfenv`, or `module`. Use `load`, `table.unpack`, and Lua 5.2 `_ENV`-based modules. See the [official library changes](https://www.lua.org/manual/5.2/manual.html#8.2).
Loading
Loading