### Install Project Dependencies Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/README.md Installs all required project dependencies defined in the package.json file using npm. This is a prerequisite for running the development server. ```bash npm install ``` -------------------------------- ### Start Local Development Server Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/README.md Starts the Docusaurus development server to preview the website locally. It enables hot-reloading for most changes made to the source files. ```bash npm run start ``` -------------------------------- ### Install and Build TypeScriptToLua Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Instructions for installing TypeScriptToLua and TypeScript as development dependencies using npm. It also shows commands for building the project and enabling watch mode for continuous compilation. ```bash # Install TypeScriptToLua and TypeScript as dev dependencies npm install --save-dev typescript-to-lua typescript # Build your project npx tstl # Build with watch mode npx tstl --watch ``` -------------------------------- ### Full tsconfig.json Configuration Example for TSTL Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt An extensive tsconfig.json example showcasing various TSTL configuration options, including Lua target, build mode, file extensions, plugin integration, and bundling. ```json { "compilerOptions": { "target": "ESNext", "lib": ["ESNext"], "moduleResolution": "Node", "types": ["@typescript-to-lua/language-extensions", "lua-types/jit"], "strict": true, "declaration": true, "plugins": [{ "transform": "dota-lua-types/transformer" }] }, "tstl": { "luaTarget": "5.4", "buildMode": "library", "extension": ".lua", "noImplicitSelf": false, "noImplicitGlobalVariables": false, "noHeader": false, "luaLibImport": "require", "sourceMapTraceback": true, "luaBundle": "bundle.lua", "luaBundleEntry": "./src/main.ts", "luaPlugins": [ { "name": "./plugin.js" }, { "name": "tstl-plugin-package" } ], "noResolvePaths": ["unresolvedModule"], "tstlVerbose": false } } ``` -------------------------------- ### npm Scripts for TSTL Build and Watch Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Example package.json configuration demonstrating how to set up npm scripts for building the project with TypeScriptToLua and running it in watch mode. ```json { "private": true, "scripts": { "build": "tstl", "dev": "tstl --watch" }, "devDependencies": { "typescript-to-lua": "^1.34.0", "typescript": "^5.5.2" } } ``` -------------------------------- ### Declaration Merging: Namespaces Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Explains and demonstrates declaration merging for namespaces, using the `love` and `string` namespaces as examples. ```APIDOC ## Declaration Merging: Namespaces ### Description This section covers declaration merging for namespaces in TypeScriptToLua, using the `love` and `string` namespaces to illustrate how to combine declarations. ### Method N/A (Declaration Merging Example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example (Namespace Definitions) ```typescript declare namespace love { export let update: (delta: number) => void; /** @tupleReturn */ export function getVersion(delta: number): [number, number, number, string]; export namespace graphics { function newImage(filename: string): Image; } } // This namespace merges with its previous declaration /** @noSelf */ declare namespace love { export let update: (delta: number) => void; } /** @noSelf */ declare namespace string { function byte(s: string, i?: number, j?: number): number; } ``` ### Code Example (Usage) ```typescript let [a, b, c, d] = love.getVersion(); let p = love.graphics.newImage("file.png"); ``` ``` -------------------------------- ### Install TypeScriptToLua dependencies Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/getting-started.md Installs the TypeScriptToLua compiler and TypeScript as development dependencies in your project. ```bash npm install --save-dev typescript-to-lua typescript ``` -------------------------------- ### Configuring TSTL Plugins in tsconfig.json Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Example configuration for enabling custom plugins within the project's tsconfig.json file. ```json { "tstl": { "luaPlugins": [ { "name": "./custom-plugin.ts" }, { "name": "published-tstl-plugin" } ] } } ``` -------------------------------- ### Lua Event Handlers Example Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/assigning-global-variables.md Demonstrates basic Lua functions that can be called by a host application as event handlers. These are typically defined globally. ```lua function OnStart() -- start event handling code end function OnStateChange(newState) -- state change event handler code end ``` -------------------------------- ### Execute TypeScriptToLua CLI Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/getting-started.md Runs the TSTL compiler using npx to execute the locally installed binary. ```bash npx tstl ``` -------------------------------- ### Implement beforeTransform Hook in TypeScriptToLua Plugin Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/plugins.md This TypeScript example shows a plugin implementing the 'beforeTransform' hook. This function is called after gathering compiler options but before transformation, allowing for setup or logging, as demonstrated by printing program and options. ```typescript import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; class Plugin implements tstl.Plugin { public beforeTransform(program: ts.Program, options: tstl.CompilerOptions, emitHost: tstl.EmitHost) { console.log("Starting transformation of program", program, "with options", options); } } const plugin = new Plugin(); export default plugin; ``` -------------------------------- ### Configuring TypeScript Environment Libraries Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Example of configuring the tsconfig.json to limit global declarations to ECMAScript standards. ```json { "compilerOptions": { "lib": ["esnext"] } } ``` -------------------------------- ### Consuming Lua Packages from npm Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/external-code.md Explains the process of installing and importing Lua-based packages from npm. These packages must include .d.ts files to be compatible with TSTL. ```bash npm install foo --save ``` ```typescript import { someFunction } from "foo"; someFunction(); ``` -------------------------------- ### Promise Execution Order: ECMAScript Output Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/caveats.md Shows the expected output in a standard JavaScript environment for the provided Promise example. The 'done' message appears after 'after' due to deferred promise reaction. ```plaintext construct after done <-- note: resolve called synchronously after 'construct' but deferred until after 'done' ``` -------------------------------- ### Promise Execution Order: TSTL Output Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/caveats.md Illustrates the output produced by TSTL for the same Promise example. Promises are resolved immediately, leading to the 'done' message appearing before 'after'. ```plaintext construct done <-- promise already resolved during construction after ``` -------------------------------- ### Declaration Merging: Function + Table Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Demonstrates declaration merging for a function that also has table-like properties, using the `assert` example from Busted. ```APIDOC ## Declaration Merging: Function + Table ### Description This section shows how to use declaration merging with a function that also has table-like properties, exemplified by the `assert` function in the Busted testing suite. ### Method N/A (Declaration Merging Example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example (TypeScript Definitions) ```typescript declare function assert(value: any, errorDescription?: string): void; declare namespace assert { export function isEqual(): void; } ``` ### Code Example (Usage) ```typescript assert.isEqual(); assert(); ``` ``` -------------------------------- ### LuaTable, LuaMap, LuaSet: Direct Lua Table Manipulation Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Demonstrates the usage of LuaTable, LuaMap, and LuaSet for direct manipulation of Lua tables with non-string keys. These classes provide methods for setting, getting, deleting, and iterating over table elements, mimicking standard collection behaviors in TypeScript while translating to Lua's table operations. ```typescript const tbl = new LuaTable(); const key1 = { id: 1 }; const key2 = { id: 2 }; tbl.set(key1, "first value"); tbl.set(key2, "second value"); print(tbl.get(key1)); // "first value" print(tbl.has(key1)); // true tbl.delete(key1); print(tbl.length()); // Get array-like length for (const [k, v] of tbl) { print(k, v); } const map = new LuaMap(); map.set("score", 100); map.set("lives", 3); const score = map.get("score"); if (score !== undefined) { print(`Score: ${score}`); } for (const [key, value] of map) { print(`${key} = ${value}`); } const visited = new LuaSet(); visited.add("nodeA"); visited.add("nodeB"); visited.add("nodeA"); print(visited.has("nodeA")); // true print(visited.has("nodeC")); // false visited.delete("nodeB"); for (const node of visited) { print(`Visited: ${node}`); } ``` -------------------------------- ### TSTL Local Variable Limit: Transpiled Lua Example Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/caveats.md Demonstrates how a simple TypeScript constant is transpiled into a Lua local variable. This highlights the potential for exceeding Lua's 200 local variable limit in large TSTL projects. ```lua local foo = 123 ``` -------------------------------- ### TypeScript to Lua Global Function Translation Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/assigning-global-variables.md Shows how TypeScript functions, when translated to Lua by TSTL, become local by default. This example contrasts the TypeScript input with its Lua output, highlighting the need for explicit global registration. ```typescript function OnStart(this: void) { // start event handling code } function OnStateChange(this: void, newState: State) { // state change event handler code } ``` ```lua local function OnStart() end local function OnStateChange(newState) end ``` -------------------------------- ### Instantiate and Use the Transpiler Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/overview.md Demonstrates how to initialize the Transpiler class and execute the emit method. It shows both the standard usage and how to inject a custom EmitHost for specialized file handling. ```typescript import * as tstl from "typescript-to-lua"; const { emitSkipped, diagnostics } = new tstl.Transpiler().emit(emitOptions); // Provide a custom emitHost for custom reading/writing of files: const { emitSkipped, diagnostics } = new tstl.Transpiler(customEmitHost).emit(emitOptions); ``` -------------------------------- ### LuaMap and LuaSet Usage Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/language-extensions.md Explains LuaMap and LuaSet as performant alternatives to standard Map/Set, detailing their methods and iteration patterns. ```APIDOC ### `LuaMap` and `LuaSet` `LuaMap` and `LuaSet` represent Lua tables used as maps or sets, offering better performance than standard `Set`/`Map` but with fewer features. - `LuaMap` provides `get` which returns `V | undefined`, similar to JavaScript's `Map`. - `LuaSet` uses an `add` method that transpiles to `table[value] = true`. - Read-only variants `ReadonlyLuaMap` and `ReadonlyLuaSet` are also available. #### Iterating over `LuaMap` & `LuaSet` Iteration is similar to `LuaTable`: ```ts // For LuaMap const luaMap = new LuaMap(); for (const [key, value] of luaMap) { // ... } // For LuaSet const luaSet = new LuaSet(); for (const value of luaSet) { // ... } ``` (Both loops transpile to using `pairs`.) #### `Map`/`Set` vs. `LuaMap`/`LuaSet` Use `Map`/`Set` for features like `keys`, `entries`, `values`, `clear`, `size`, and guaranteed insertion order. Use `LuaMap`/`LuaSet` when: - The table needs to be serialized. - Interacting with other Lua libraries. - Performance is critical (measure first!). ``` -------------------------------- ### Advanced Transpilation with Custom Options and Plugins Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/overview.md Shows how to configure a TypeScript program from a config file, define custom emit behavior using the writeFile callback, and apply plugins during the transpilation process. ```typescript import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; const configFileName = path.resolve(__dirname, "tsconfig.json"); const parsedCommandLine = tstl.parseConfigFileWithSystem(configFileName); parsedCommandLine.options.luaTarget = tstl.LuaTarget.Lua54; const program = ts.createProgram(parsedCommandLine.fileNames, parsedCommandLine.options); const extraSourceFile = ts.createSourceFile("my-source-file.ts", "// my ts code"); const emitResults: Record = {}; const { diagnostics } = new tstl.Transpiler().transpile({ program, sourceFiles: [extraSourceFile], writeFile(fileName, data) { emitResults[fileName] = data; }, plugins: [ { beforeTransform(program, CompilerOptions, emitHost) { console.log("before transforming plugin hook!"); }, afterPrint(program, options, emitHost, result) { console.log("after printing plugin hook!"); }, }, ], }); ``` -------------------------------- ### Programmatic Transpilation with Custom Emit Host Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Demonstrates how to manually parse a tsconfig, create a TypeScript program, and use the TSTL Transpiler class to emit Lua code into memory. It includes custom plugins to modify output during the transformation lifecycle. ```typescript import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; import * as path from "path"; const configFileName = path.resolve(__dirname, "tsconfig.json"); const parsedCommandLine = tstl.parseConfigFileWithSystem(configFileName); if (parsedCommandLine.errors.length > 0) { const reportDiagnostic = tstl.createDiagnosticReporter(true); parsedCommandLine.errors.forEach(reportDiagnostic); process.exit(1); } parsedCommandLine.options.luaTarget = tstl.LuaTarget.Lua54; parsedCommandLine.options.sourceMapTraceback = true; const program = ts.createProgram( parsedCommandLine.fileNames, parsedCommandLine.options ); const emitResults: Record = {}; const { diagnostics } = new tstl.Transpiler().emit({ program, writeFile(fileName, data) { emitResults[fileName] = data; }, plugins: [ { beforeTransform(program, options, emitHost) { console.log("Starting transformation..."); }, afterPrint(program, options, emitHost, result) { for (const file of result) { file.code = `-- Generated at ${new Date().toISOString()}\n` + file.code; } }, afterEmit(program, options, emitHost, result) { console.log(`Emitted ${result.length} files`); }, }, ], }); const reportDiagnostic = tstl.createDiagnosticReporter(true); const allDiagnostics = ts.sortAndDeduplicateDiagnostics([ ...ts.getPreEmitDiagnostics(program), ...diagnostics, ]); allDiagnostics.forEach(reportDiagnostic); Object.entries(emitResults).forEach(([fileName, content]) => { console.log(`\n--- ${fileName} ---\n${content}`); }); ``` -------------------------------- ### Importing Local Lua Files with Type Declarations Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/external-code.md Demonstrates how to include a Lua file in a project by providing a corresponding TypeScript declaration file. This allows the TypeScript compiler to recognize the functions exported by the Lua module. ```typescript import { foo, bar } from "./someLua"; foo(); bar(); ``` ```lua local someLua = {} function someLua:foo() print("hello") end function someLua:bar() print("world") end return someLua ``` ```typescript export function foo(): void; export function bar(): void; ``` -------------------------------- ### Define npm build scripts Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/getting-started.md Configures package.json scripts to simplify the build process and enable watch mode. ```json { "private": true, "scripts": { "build": "tstl", "dev": "tstl --watch" }, "devDependencies": { "typescript-to-lua": "..." } } ``` -------------------------------- ### Run npm build commands Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/getting-started.md Executes the defined build scripts for standard compilation or development watch mode. ```bash npm run build npm run dev ``` -------------------------------- ### Declaration Merging: Classes Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Details how class declarations are handled in TypeScriptToLua, emphasizing that `declare class` is generally not recommended for Lua values and suggesting interfaces instead, with examples for table-based classes. ```APIDOC ## Declaration Merging: Classes ### Description This section explains the handling of `class` declarations in TypeScriptToLua. It clarifies that `declare class` is primarily for TypeScript compatibility and not typically used for Lua values. Interfaces are recommended for simulating Lua classes. Two examples demonstrate common Lua class patterns. ### Method N/A (Declaration Merging Example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Example 1: Table with Static `new` Method #### Lua Code ```lua Box = {} Box.__index = Box function Box.new(value) local self = {} setmetatable(self, Box) self._value = value return self end function Box:get() return self._value end ``` #### TypeScript Definitions ```typescript interface Box { get(): string; } interface BoxConstructor { new: (this: void, value: string) => Box; } declare var Box: BoxConstructor; ``` #### Usage Example ```typescript // Usage const box = Box.new("foo"); box.get(); ``` ### Example 2: Callable Table with Static Methods #### Lua Code ```lua Box = {} local instance function Box:getInstance() if instance then return instance end instance = Box("instance") return instance end setmetatable(Box, { __call = function(_, value) return { get = function() return value end } end }) ``` #### TypeScript Definitions ```typescript interface Box { get(): string; } interface BoxConstructor { (this: void, value: string): Box; getInstance(): Box; } declare var Box: BoxConstructor; ``` #### Usage Example ```typescript // Usage const box = Box("foo"); box.get(); Box.getInstance().get(); ``` ``` -------------------------------- ### Modify String Literal Transformation in TypeScriptToLua Plugin Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/plugins.md This TypeScript example shows a plugin that customizes the visitor for 'StringLiteral'. It uses 'context.superTransformExpression' to call the default transformer and then modifies the resulting string literal's value to 'bar'. ```typescript import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; const plugin: tstl.Plugin = { visitors: { [ts.SyntaxKind.StringLiteral]: (node, context) => { const result = context.superTransformExpression(node); if (tstl.isStringLiteral(result)) { result.value = "bar"; } return result; }, }, }; export default plugin; ``` -------------------------------- ### Transpile TypeScript Project from tsconfig.json using API Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Shows how to transpile an entire TypeScript project defined by a tsconfig.json file using the `transpileProject` function. It includes checking for transpilation diagnostics. ```typescript import * as tstl from "typescript-to-lua"; // Transpile an entire project from tsconfig.json const projectResult = tstl.transpileProject("./tsconfig.json", { luaTarget: tstl.LuaTarget.Lua54 }); if (projectResult.diagnostics.length > 0) { projectResult.diagnostics.forEach(d => console.error(d.messageText)); } else { console.log("Project transpiled successfully!"); } ``` -------------------------------- ### Iterating over LuaTable Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/language-extensions.md Demonstrates how to iterate over a LuaTable using a for...of loop, which transpiles to Lua's pairs() function. ```APIDOC ## Iterating over `LuaTable` To iterate over a `LuaTable`, use `for...of`. This will generate a `for...in` statement using `pairs()`. ### TypeScript Example ```ts const tbl = new LuaTable(); tbl.set(3, "bar"); tbl.set(4, "bar"); tbl.set(5, "bar"); for (const [key, value] of tbl) { console.log(key); console.log(value); } ``` ### Lua Output ```lua tbl = {} tbl[3] = "bar" tbl[4] = "bar" tbl[5] = "bar" for key, value in pairs(tbl) do print(key) print(value) end ``` (Note: `pairs()` in Lua returns keys in a random order.) ``` -------------------------------- ### Lua Table Manipulation with LuaTable Type Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/language-extensions.md Illustrates how to use the `LuaTable` type in TypeScript to create and manipulate Lua tables, especially when using non-string keys. Methods like `get`, `set`, `has`, and `delete` are provided for direct translation to Lua table operations. ```typescript const typedLuaTable = new LuaTable(); const untypedLuaTable = new LuaTable(); // Same as LuaTable ``` ```typescript const tbl = new LuaTable(); tbl.set("foo", "bar"); console.log(tbl.get("foo")); const objectKey = {}; tbl.set(objectKey, "baz"); console.log(tbl.get(objectKey)); tbl.set(1, "bah"); console.log(tbl.length()); ``` ```lua tbl = {} tbl.foo = "bar" print(tbl.foo) objectKey = {} tbl[objectKey] = "baz" print(tbl[objectKey]) tbl[1] = "bah" print(#tbl) ``` -------------------------------- ### Defining Namespaces and Modules Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Shows how to define ambient namespaces and modules to map Lua tables or require-able modules to TypeScript structures. ```typescript declare namespace table { /** @noSelf */ export function insert(table: object, item: any): number; } declare module "utf8" { /** @noSelf */ export function codepoint(): void; } ``` ```typescript table.insert({}, 1); import * as utf8 from "utf8"; utf8.codepoint(); ``` -------------------------------- ### Importing External Lua Code with TypeScript Declarations Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt This snippet demonstrates how to import and use existing Lua modules within a TypeScript project. It includes a Lua module (mathlib.lua) and its corresponding TypeScript declaration file (mathlib.d.ts) for type safety, along with an example of importing and using the module in TypeScript (main.ts). ```lua -- mathlib.lua local mathlib = {} function mathlib.lerp(a, b, t) return a + (b - a) * t end function mathlib.clamp(value, min, max) return math.max(min, math.min(max, value)) end return mathlib ``` ```typescript -- mathlib.d.ts - Declaration file for the Lua module /** @noSelf */ declare module "./mathlib" { export function lerp(a: number, b: number, t: number): number; export function clamp(value: number, min: number, max: number): number; } -- main.ts - Import and use the Lua module import { lerp, clamp } from "./mathlib"; const interpolated = lerp(0, 100, 0.5); // 50 const clamped = clamp(150, 0, 100); // 100 print(`Interpolated: ${interpolated}, Clamped: ${clamped}`); ``` -------------------------------- ### Publishing Declarations to npm Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Provides the command-line workflow for publishing declaration packages and configuring tsconfig.json to consume them. ```bash npm init npm login npm publish --dry-run npm version 0.0.1 npm publish npm install --save-dev ``` ```json { "compilerOptions": { "types": ["declarations"] } } ``` -------------------------------- ### LuaMultiReturn Type for Multiple Return Values in TypeScript Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt This example shows how to declare and use functions that return multiple values in Lua from TypeScript using the `LuaMultiReturn` type. It requires enabling language extensions in `tsconfig.json`. The code demonstrates destructuring assignment for capturing multiple returns and using the `$multi` helper function to return multiple values. ```typescript // Enable language extensions in tsconfig.json // "types": ["@typescript-to-lua/language-extensions"] // Declare a function that returns multiple values declare namespace string { function find(haystack: string, needle: string): LuaMultiReturn<[number, number]>; function gsub(s: string, pattern: string, repl: string): LuaMultiReturn<[string, number]>; } // Use destructuring to capture multiple return values const [start, finish] = string.find("Hello, world!", "world"); print(`Found at: ${start} to ${finish}`); // Lua output: local start, finish = string.find("Hello, world!", "world") const [result, count] = string.gsub("hello hello", "hello", "hi"); print(`Result: ${result}, Replacements: ${count}`); // Create a function that returns multiple values using $multi function divmod(a: number, b: number): LuaMultiReturn<[number, number]> { return $multi(Math.floor(a / b), a % b); } const [quotient, remainder] = divmod(17, 5); print(`17 / 5 = ${quotient} remainder ${remainder}`); // Lua output: local quotient, remainder = divmod(17, 5) // Nested multi-return with error handling function safeDivide(a: number, b: number): LuaMultiReturn<[number | nil, string | nil]> { if (b === 0) { return $multi(nil, "Division by zero"); } return $multi(a / b, nil); } const [value, err] = safeDivide(10, 0); if (err) { print(`Error: ${err}`); } else { print(`Result: ${value}`); } ``` -------------------------------- ### Declaration Merging: Interfaces Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Illustrates declaration merging for interfaces, showing how to combine declarations for the `Image` interface. ```APIDOC ## Declaration Merging: Interfaces ### Description This example demonstrates declaration merging for interfaces in TypeScriptToLua. It shows how multiple declarations for the same interface can be combined. ### Method N/A (Declaration Merging Example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example (Interface Definitions) ```typescript interface Image { /** @tupleReturn */ getDimensions(): [number, number]; } // This interface merges with its previous declaration /** @noSelf */ interface Image { getFlags(): object; } ``` ### Code Example (Usage) ```typescript declare let image: Image; let [w, h] = image.getDimensions(); // local w, h = image:getDimensions() let o = image.getFlags(); ``` ``` -------------------------------- ### Custom Getters and Setters for Lua Tables Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/language-extensions.md Illustrates how to define custom getters and setters for Lua tables with non-string keys using LuaTableGet and LuaTableSet. ```APIDOC ### Custom Getters and Setters For types using non-string keys, `LuaTableGet` and `LuaTableSet` function types allow custom getters and setters. #### Example using Method Types ```ts interface Id { idStr: string; } interface IdDictionary { get: LuaTableGetMethod; set: LuaTableSetMethod; } declare const dict: IdDictionary; const id: Id = { idStr: "foo" }; // Using set method dict.set(id, "bar"); // Using get method console.log(dict.get(id)); ``` #### Transpiled Lua Output ```lua id = {idStr = "foo"} dict[id] = "bar" print(dict[id]) ``` #### Example using Standalone Functions ```ts declare const idGet: LuaTableGet; declare const idSet: LuaTableSet; // Using standalone set function idSet(dict, id, "bar"); // Using standalone get function console.log(idGet(dict, id)); ``` #### Example using Namespace Functions ```ts declare namespace IdDictionary { export const get: LuaTableGet; export const set: LuaTableSet; } // Using namespace set function IdDictionary.set(dict, id, "bar"); // Using namespace get function console.log(IdDictionary.get(dict, id)); ``` ``` -------------------------------- ### Exporting Module Definitions Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Demonstrates how to use the 'export' keyword to define the structure of external Lua libraries or modules so they can be imported into TypeScript. ```typescript export let x: number; ``` ```typescript import { x } from "./lib"; ``` -------------------------------- ### Implementing a Custom TSTL Plugin Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Shows how to define a plugin that hooks into the TSTL transpilation lifecycle, including AST visitor modification, header injection, and custom module resolution. ```typescript import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; import { SourceNode } from "source-map"; const plugin: tstl.Plugin = { visitors: { [ts.SyntaxKind.ReturnStatement]: () => tstl.createReturnStatement([tstl.createBooleanLiteral(true)]), [ts.SyntaxKind.StringLiteral]: (node, context) => { const result = context.superTransformExpression(node); if (tstl.isStringLiteral(result)) { result.value = result.value.toUpperCase(); } return result; }, }, beforeTransform(program: ts.Program, options: tstl.CompilerOptions, emitHost: tstl.EmitHost) { console.log(`Transforming ${program.getSourceFiles().length} files`); }, afterPrint(program: ts.Program, options: tstl.CompilerOptions, emitHost: tstl.EmitHost, result: tstl.ProcessedFile[]) { for (const file of result) { file.code = `-- Custom header\n${file.code}`; } }, beforeEmit(program: ts.Program, options: tstl.CompilerOptions, emitHost: tstl.EmitHost, result: tstl.EmitFile[]) { for (const file of result) { file.code = file.code.replace(/print\(/g, "logger.info("); } }, afterEmit(program: ts.Program, options: tstl.CompilerOptions, emitHost: tstl.EmitHost, result: tstl.EmitFile[]) { result.forEach(f => console.log(`Wrote: ${f.outputPath}`)); }, moduleResolution(moduleIdentifier: string, requiringFile: string, options: tstl.CompilerOptions, emitHost: tstl.EmitHost) { if (moduleIdentifier === "@mylib") { return "libs.mylib"; } return undefined; }, }; export default plugin; ``` -------------------------------- ### Configuring and Publishing TSTL Libraries as npm Packages Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt This section details the configuration required to build a TypeScriptToLua project as a library intended for publishing on npm. It includes the tsconfig.json for compiler options, package.json for project metadata and scripts, a TypeScript entry point (src/index.ts), and bash commands for building and publishing. ```json // tsconfig.json for library { "compilerOptions": { "target": "ESNext", "lib": ["ESNext"], "moduleResolution": "Node", "declaration": true, "outDir": "./dist", "strict": true }, "tstl": { "buildMode": "library", "luaTarget": "JIT" }, "include": ["src/**/*"] } ``` ```json // package.json for library { "name": "my-tstl-library", "version": "1.0.0", "description": "A TypeScriptToLua library", "main": "./dist/index", "types": "./dist/index.d.ts", "files": [ "dist/**/*.lua", "dist/**/*.d.ts" ], "scripts": { "build": "tstl", "prepublishOnly": "npm run build" }, "devDependencies": { "typescript-to-lua": "^1.34.0", "typescript": "^5.5.2" } } ``` ```typescript // src/index.ts - Library entry point export function greet(name: string): string { return `Hello, ${name}!`; } export class Counter { private value = 0; increment(): void { this.value++; } getValue(): number { return this.value; } } export { utils } from "./utils"; ``` ```bash # Build and publish npm run build npm publish --dry-run # Preview what will be published npm publish # Publish to npm ``` -------------------------------- ### Class Declaration for Lua Tables with Constructor (Lua & TypeScript) Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Demonstrates how to declare Lua tables that simulate classes with a static 'new' method for instantiation using TypeScript interfaces and declaration files. This pattern is common for creating objects in Lua. ```lua Box = {} Box.__index = Box function Box.new(value) local self = {} setmetatable(self, Box) self._value = value return self end function Box:get() return self._value end ``` ```typescript interface Box { get(): string; } interface BoxConstructor { new: (this: void, value: string) => Box; } declare var Box: BoxConstructor; // Usage const box = Box.new("foo"); box.get(); ``` -------------------------------- ### LuaPrinter Node Visitors Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/printer.md Methods used to visit and print specific Lua AST nodes to SourceNode objects. ```APIDOC ## METHOD printStatement / printExpression ### Description Individual visitor methods for specific AST nodes. Each method takes a specific node type and returns a SourceNode representing the printed output for that node. ### Parameters #### Arguments - **node** (lua.Node) - Required - The specific AST node to visit (e.g., lua.IfStatement, lua.BinaryExpression). ### Response #### Success Response - **SourceNode** (SourceNode) - The resulting SourceNode containing the printed code and mapping information. ``` -------------------------------- ### Transpile Virtual TypeScript Files using API Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Demonstrates transpiling TypeScript code from in-memory virtual files using the `transpileVirtualProject` function. This is useful for scenarios where files are not present on the filesystem. ```typescript import * as tstl from "typescript-to-lua"; // Transpile virtual files (in-memory) const virtualResult = tstl.transpileVirtualProject( { "main.ts": `import { helper } from "./utils"; helper();`, "utils.ts": `export function helper() { print("Helper called"); }`, }, { luaTarget: tstl.LuaTarget.Lua53 } ); virtualResult.transpiledFiles.forEach(file => { console.log(`--- ${file.fileName} ---`); console.log(file.lua); }); ``` -------------------------------- ### Handle Table Key Deletion Differences (JavaScript vs. Lua) Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/caveats.md Demonstrates how JavaScript's 'delete' operator for object keys differs from Lua's 'nil' assignment. Provides a workaround for cases where 'null' or 'undefined' are used to represent initialized zero-values. ```javascript const foo = {}; foo.someProp1 = 123; foo.someProp2 = undefined; foo.someProp3 = null; for (const key of Object.keys(foo)) { console.log(key); } ``` ```typescript // Workaround for null/undefined values const foo = {}; foo.someProp1 = 123; foo.someProp2 = "__TSTL_NULL"; // Or -1, or a dedicated object foo.someProp3 = "__TSTL_NULL"; for (const key of Object.keys(foo)) { console.log(key); } ``` -------------------------------- ### Configure npm Scripts for TypeScriptToLua Builds Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/editor-support.md Defines npm scripts for building and watching TypeScriptToLua projects. The 'build' script compiles the project, while 'dev' compiles and watches for changes. ```json { "scripts": { "build": "tstl", "dev": "tstl --watch" } } ``` -------------------------------- ### Documenting functions with TSDoc Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Shows how to use TSDoc comments to provide metadata for editors and IDEs. ```typescript /** * When hovering over print, this description will be shown * @param args Stuff to print */ declare function print(...args: any[]); ``` -------------------------------- ### Configure VSCode Build Task for TypeScriptToLua Watch Mode Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/editor-support.md Sets up a default build task in VSCode to run the 'dev' npm script, which enables watch mode for TypeScriptToLua. This task uses a problem matcher to display compilation errors and runs in the background. ```json { "version": "2.0.0", "tasks": [ { "type": "npm", "script": "dev", "problemMatcher": "$tsc-watch", "isBackground": true, "presentation": { "reveal": "never" }, "group": { "kind": "build", "isDefault": true } } ] } ``` -------------------------------- ### Implement beforeEmit plugin hook Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/plugins.md The beforeEmit hook allows modification of the generated Lua code after translation and bundling but before writing to disk. It receives the program, compiler options, host, and the list of emitted files. ```typescript import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; const plugin: tstl.Plugin = { beforeEmit(program: ts.Program, options: tstl.CompilerOptions, emitHost: tstl.EmitHost, result: tstl.EmitFile[]) { for (const file of result) { file.code = "-- Comment added by beforeEmit plugin\n" + file.code; } }, }; export default plugin; ``` -------------------------------- ### Compiler Configuration Options Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/configuration.md Details on the various configuration flags that can be set in tsconfig.json to customize the TypeScriptToLua build process. ```APIDOC ## Configuration Options ### Description These options are defined within the `tsconfig.json` file under the `tstl` compiler options to modify how TypeScript is transpiled into Lua. ### Parameters - **lua51AllowTryCatchInAsyncAwait** (boolean) - Optional - Disable warning diagnostic about try/catch inside async functions for Lua 5.1. - **luaLibImport** (string) - Optional - Specifies how polyfilled functions are imported: "inline", "require", "require-minimal", or "none". - **sourceMapTraceback** (boolean) - Optional - Overrides Lua's debug.traceback to apply sourcemaps to Lua stacktraces. - **luaBundle** (string) - Optional - Path to the output bundle file. Requires luaBundleEntry. - **luaBundleEntry** (string) - Optional - Path to the TypeScript entry point file for bundling. - **luaPlugins** (Array) - Optional - List of TypeScriptToLua plugins. - **tstlVerbose** (boolean) - Optional - Enables additional logging for build diagnostics. - **noResolvePaths** (Array) - Optional - List of require paths that should not be resolved by the compiler. ### Request Example { "tstl": { "luaLibImport": "require-minimal", "sourceMapTraceback": true, "tstlVerbose": false } } ``` -------------------------------- ### Transpile TypeScript String to Lua using API Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Demonstrates using the high-level TypeScriptToLua API to transpile a string of TypeScript code directly into Lua code. It shows how to specify Lua target options. ```typescript import * as tstl from "typescript-to-lua"; // Transpile a string of TypeScript code const stringResult = tstl.transpileString( `const greeting = "Hello, Lua!"; print(greeting);`, { luaTarget: tstl.LuaTarget.Lua53 } ); console.log(stringResult.file?.lua); // Output: local greeting = "Hello, Lua!" print(greeting) ``` -------------------------------- ### Managing Imports and Exports in Declarations Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/writing-declarations.md Shows how to include global declarations and re-export types within index.d.ts files or ambient modules. ```typescript import "./lib"; export { Player } from "./Entities"; declare module "mymodule" { import * as types from "types"; export function getType(): types.Type; } ``` -------------------------------- ### beforeEmit Hook Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/plugins.md The beforeEmit hook allows modification of the generated Lua code after translation and bundling but before writing to disk. ```APIDOC ## beforeEmit ### Description Called after the input program has been translated to Lua, after external dependencies have been resolved and included, and after bundling. ### Parameters - **program** (ts.Program) - The TypeScript program object. - **options** (tstl.CompilerOptions) - The compiler options used. - **emitHost** (tstl.EmitHost) - The host interface for emitting files. - **result** (tstl.EmitFile[]) - The list of files to be emitted. ### Request Example ```ts const plugin: tstl.Plugin = { beforeEmit(program, options, emitHost, result) { for (const file of result) { file.code = "-- Comment\n" + file.code; } } };``` ``` -------------------------------- ### Transpile Multiple TypeScript Files to Lua using API Source: https://context7.com/typescripttolua/typescripttolua.github.io/llms.txt Illustrates transpiling multiple TypeScript files into Lua using the `transpileFiles` function from the TypeScriptToLua API. It includes error handling for diagnostics and processing emitted files. ```typescript import * as tstl from "typescript-to-lua"; // Transpile multiple files const filesResult = tstl.transpileFiles( ["./src/main.ts", "./src/utils.ts"], { luaTarget: tstl.LuaTarget.LuaJIT } ); filesResult.diagnostics.forEach(d => console.error(d.messageText)); filesResult.emitResult.forEach(file => { console.log(`${file.name}: ${file.text}`); }); ``` -------------------------------- ### Declaring and Assigning Global Variables in TypeScript Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/assigning-global-variables.md Illustrates how to declare global variables using `declare var` and then assign values to them in TypeScript. This approach is useful for environments where global APIs are expected. ```typescript declare var OnStart: (this: void) => void; declare var OnStateChanged: (this: void, newState: State) => void; OnStart = () => { // start event handling code }; OnStateChanged = (newState: State) => { // state change event handler code }; ``` -------------------------------- ### Configure TypeScriptToLua Plugins in tsconfig.json Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/plugins.md This JSON snippet shows how to configure TypeScriptToLua plugins by adding them to the 'luaPlugins' option in the tsconfig.json file. It demonstrates including local JavaScript/TypeScript plugins and plugins published via npm. ```json { "tstl": { "luaPlugins": [ { "name": "./plugin1.js" }, { "name": "./plugin2.ts" }, { "name": "tstl-plugin-3" } ] } } ``` -------------------------------- ### Configure npm Package Manifest Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/publishing-modules.md Required fields in package.json to ensure the library is correctly packaged and discoverable by TSTL consumers. Specifies the entry point and the files to be included in the npm bundle. ```json { "files": [ "dist/**/*.lua", "dist/**/*.d.ts" ], "types": "./dist/index.d.ts", "main": "./dist/index" } ``` -------------------------------- ### Configure TypeScriptToLua Library Settings Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/publishing-modules.md Required compiler options for a TSTL library project. The buildMode must be set to library to enable proper transpilation for distribution. ```json { "compilerOptions": { "declaration": true }, "tstl": { "buildMode": "library" } } ``` -------------------------------- ### TranspileProject API Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/api/overview.md Transpiles a TypeScript project defined by a tsconfig.json file to Lua. ```APIDOC ## POST /transpile/project ### Description Transpiles a TypeScript project to Lua. ### Method POST ### Endpoint /transpile/project ### Parameters #### Request Body - **tsConfigPath** (string) - Required - The file path to a TypeScript project's `tsconfig.json` file. - **extendedOptions** (tstl.CompilerOptions) - Optional - CompilerOptions to extend the tsconfig options. ### Request Example ```json { "tsConfigPath": "tsconfig.json", "extendedOptions": { "luaTarget": "Lua53" } } ``` ### Response #### Success Response (200) - **diagnostics** (tstl.Diagnostic[]) - An array of diagnostics reported during transpilation. - **emitResult** (tstl.EmitResult) - The result of the project emission. #### Response Example ```json { "diagnostics": [], "emitResult": { "emitSkipped": false, "emittedFiles": ["file1.lua", "file2.lua"] } } ``` ``` -------------------------------- ### All Custom Lua Table Functions Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/language-extensions.md Lists and briefly describes the available custom Lua table functions for advanced table manipulation in TypeScript. ```APIDOC ### All custom Lua table functions Beyond getters and setters, TSTL provides several utility functions for Lua table manipulation: - `LuaTableGet`: Standalone function to retrieve a value by key. - `LuaTableGetMethod`: Method to retrieve a value by key from the containing table. - `LuaTableSet`: Standalone function to set a value by key. - `LuaTableSetMethod`: Method to set a value by key in the containing table. - `LuaTableHas`: Standalone function to check for key existence. - `LuaTableHasMethod`: Method to check for key existence in the containing table. - `LuaTableDelete`: Standalone function to remove a key-value pair. - `LuaTableDeleteMethod`: Method to remove a key-value pair from the containing table. - `LuaTableAddKey`: Standalone function to set a key's value to `true`. - `LuaTableAddKeyMethod`: Method to set a key's value to `true` in the containing table. ``` -------------------------------- ### Import JSON Data in TypeScript Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/json-modules.md Demonstrates how to import a JSON file as a module in TypeScript. The imported JSON data can then be accessed using standard object property access. ```typescript import * as myJson from "./myjsondata.json"; const p1 = myJson.property1; ``` -------------------------------- ### Namespace-based Custom Getters and Setters for LuaTable Source: https://github.com/typescripttolua/typescripttolua.github.io/blob/source/docs/advanced/language-extensions.md Shows how to implement custom getters and setters for Lua tables using namespace declarations, allowing for a more structured approach to custom table access. ```typescript interface Id { idStr: string; } interface IdDictionary { // ... } declare namespace IdDictionary { export const get: LuaTableGet; export const set: LuaTableSet; } IdDictionary.set(dict, id, "bar"); console.log(IdDictionary.get(dict, id)); ```