Skip to content

Commit fb23b40

Browse files
authored
adding "Importing Arrays" section (#59)
* adding "Importing Arrays" section * Update external-lua-code.md * Update external-lua-code.md * rewriting
1 parent f62a2b5 commit fb23b40

File tree

1 file changed

+65
-7
lines changed

1 file changed

+65
-7
lines changed

docs/external-lua-code.md

Lines changed: 65 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,78 @@ You can simply add a Lua file as part of your project sources if you add [a decl
1111
Your project should look like:
1212

1313
```
14-
main.ts
15-
somelua.lua
16-
somelua.d.ts
17-
tsconfig.json
14+
project/
15+
├── main.ts
16+
├── someLua.lua
17+
├── someLua.d.ts
18+
└── tsconfig.json
1819
```
1920

20-
And you can use it like so:
21+
```ts title=main.ts
22+
import { foo, bar } from "./someLua";
23+
24+
foo();
25+
bar();
26+
```
27+
28+
```lua title=someLua.lua
29+
local someLua = {}
30+
31+
function someLua:foo()
32+
print("hello")
33+
end
34+
35+
function someLua:bar()
36+
print("world")
37+
end
38+
39+
return someLua
40+
```
41+
42+
```ts title=someLua.d.ts
43+
export function foo(): void;
44+
export function bar(): void;
45+
```
46+
47+
## Importing a Lua module that only exports an array
48+
49+
Building on the previous section, you might want also want to import a Lua file that only exports an array. For example, something like:
50+
51+
```lua title=things.lua
52+
return {
53+
{
54+
foo = 123,
55+
bar = 456,
56+
},
57+
{
58+
foo = 789,
59+
bar = 987,
60+
},
61+
}
62+
```
63+
64+
Writing a definitions file for this is tricky, since the Lua file has no named imports and no default export. Here, you have to use `export =` syntax, like so:
65+
66+
```ts title=things.d.ts
67+
interface Thing {
68+
foo: number;
69+
bar: number;
70+
}
71+
72+
declare const things: Thing[];
73+
export = things;
74+
```
75+
76+
Then, in your TypeScript code, you can import it like:
2177

2278
```ts title=main.ts
23-
import { myFunction } from "./somelua";
79+
import * as things from "./module";
2480

25-
myFunction();
81+
print(things[0].foo); // Prints "123"
2682
```
2783

84+
For more information about this export syntax, see [the official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require).
85+
2886
## Using NPM packages
2987

3088
To use a Lua package, install it via npm and use it as you would for any regular npm package in TypeScript. If the package does not include its own `.d.ts` declaration files, you can create your own by adding a `<package name>.d.ts` [declaration file](./advanced/writing-declarations.md) to your source files.

0 commit comments

Comments
 (0)