|
| 1 | +--- |
| 2 | +title: Language extensions |
| 3 | +--- |
| 4 | + |
| 5 | +import { SideBySide } from "@site/src/components/SideBySide"; |
| 6 | + |
| 7 | +TypeScriptToLua provides several extensions to the TypeScript language in the form of types and helper functions. To use these language extensions, add the types to your `tsconfig.json`: |
| 8 | + |
| 9 | +```json |
| 10 | +{ |
| 11 | + "compilerOptions": { |
| 12 | + ... |
| 13 | + "types": ["typescript-to-lua/language-extensions"], |
| 14 | + ... |
| 15 | + }, |
| 16 | +} |
| 17 | +``` |
| 18 | + |
| 19 | +## MultiReturn Type |
| 20 | + |
| 21 | +This language extension allows typing of Lua functions that return multiple values. For example, consider Lua's `string.find`, it returns two indices: the start of the found substring and the end of the found substring. In TypeScript, functions can only return one value so a special type is needed to indicate to tstl there are multiple return values. This is the `MultiReturn<>` type. |
| 22 | + |
| 23 | +It allows us to declare `string.find` like this: |
| 24 | + |
| 25 | +```ts title=stringfind.ts |
| 26 | +declare namespace string { |
| 27 | + export function find(haystack: string, needle: string): MultiReturn<[number, number]>; |
| 28 | +} |
| 29 | + |
| 30 | +const [start, end] = string.find("Hello, world!", "world"); |
| 31 | +``` |
| 32 | + |
| 33 | +Translating into: |
| 34 | + |
| 35 | +```lua title=stringfind.lua |
| 36 | +start, ____end = string.find("Hello, world!", "world") |
| 37 | +``` |
| 38 | + |
| 39 | +:::note |
| 40 | +Prefer MultiReturn over the similar [@tupleReturn annotation](./compiler-annotations.md#tuplereturn). MultiReturn can do anything tupleReturn can, with the added benefit of being able to distinguish between actual tuple tables and multiple return values in the type system. |
| 41 | +::: |
| 42 | + |
| 43 | +### \$multi |
| 44 | + |
| 45 | +In order to create a function that returns multiple values it needs to return a `MultiReturn<>` type. This is where the `$multi` function comes in. Calling `$multi` in a return statement will create an instance of the `MultiReturn<>` type: |
| 46 | + |
| 47 | +```ts title=multi.ts |
| 48 | +function myFunc(): MultiReturn<[string, number]> { |
| 49 | + return $multi("foo", 4); |
| 50 | +} |
| 51 | + |
| 52 | +const [foo, four] = myFunc(); |
| 53 | +``` |
| 54 | + |
| 55 | +Translates into: |
| 56 | + |
| 57 | +```lua title=multi.lua |
| 58 | +function myFunc(self) |
| 59 | + return "foo", 4 |
| 60 | +end |
| 61 | +foo, four = myFunc(nil) |
| 62 | +``` |
0 commit comments