luau-lang / luau

A fast, small, safe, gradually typed embeddable scripting language derived from Lua
https://luau-lang.org
MIT License
3.79k stars 348 forks source link

Module Declaration for Native Modules #1225

Open flakey5 opened 2 months ago

flakey5 commented 2 months ago

Background

Hey all! I'm working on a small side project and one of the things I'd like to do involves porting some Lua code over to Luau. The current code exposes a lot of native modules that can be used via require() statements. E.g.

local someLibrary = require('some-c-library')

Luau doesn't like this since it can't find the module. From what I've seen looking at docs and rfcs, I don't think there's currently a way to do this that Luau likes. It looks like the current declaration syntax only works for declaring globals.

Proposal

Adding modules to the current declaration syntax. Something like,

-- types.d.luau
-- Module exporting a table
declare module 'some-c-library' {
  sum: (a: number, b: number) -> number
    -- ...other module exports here
}

-- Module exporting a string
declare module 'some-other-library' string

-- some-source-file.luau
local someLibrary = require('some-c-library')
print(someLibrary.sum(1, 2))
print(require('some-other-library'))

This would,

Mooshua commented 2 months ago

Luau doesn't like this since it can't find the module. From what I've seen looking at docs and rfcs, I don't think there's currently a way to do this that Luau likes. It looks like the current declaration syntax only works for declaring globals.

The way to do this in a way that luau "likes" is to create a module resolver compatible with the Analysis library. This allows the analyzer to discover built-in module types at compile time. You can check the CLI implementation at struct CliFileResolver : Luau::FileResolver in Analyze.cpp.

Note that this means you will probably need to ship your own analysis binaries that use your fancy custom file resolver.