tech

[English] [Japanese]

22. require/module

This time I will explain how to handle Lua modules from LuneScript.

require

Use require() when dealing with Lua modules.

The specification of require() is the same as Lua, but the return value is stem. that is, it has no type information. A proper cast is required.

module

As above, require() returns a stem.

Since stem has no type information, it is not very useful.

So we use the module declaration.

For example, if you have a Lua module Test.lua like this:

local mod = {}
mod.val = 1;
function mod.func1( val )
   return val + 10
end
function mod:func2( val )
   return self.val + val
end
return mod

This Test.lua module has the following elements:

  • member val of int
  • function func1
  • method func2

The function mentioned here is called with . like obj.func1(), and the method is called with : like obj:func1().

A module declaration that uses this Test.lua module is done as follows.

// @lnsFront: skip
module Test require 'Test'
{
   pub static let val:int;
   pub static fn func1( val:int ):int;
   pub fn func2( val:int ):int;
}
print( Test.val, Test.func1( 10 ), Test.func2( 20 ) ); // 1 20 21

First, module Test in module Test require 'Test' declares the module name Test. Think of the module name as a normal class name. Here, I used the same name as the Lua module name, but there is no problem with a different name.

require 'Test' in module Test require 'Test' specifies which module to load. Here we specify that we are loading the Test module.

The rest is the same as a normal class declaration.

A module declared module is accessed by the module name.

// @lnsFront: skip
print( Test.val, Test.func1( 10 ), Test.func2( 20 ) );

Lua APIs not built in by LuneScript

LuneScript has built-in the minimum standard Lua API for self-hosting.

You can't directly access Lua's standard APIs that aren't built-in (e.g. math.pi).

To access APIs that are not built-in, they are made available by declaring them as modules, like this:

// @lnsFront: ok
module Math require 'math' {
   pub static let pi:real;
   pub static fn sin(x:real):real;
}

print( Math.pi, Math.sin(Math.pi/2) );  // 3.1415926535898	1.0

Restrictions on module declarations

module declarations have the following restrictions:

  • You cannot declare a new class by inheriting from a module
  • Do not check the consistency between the required Lua module and the declared module

    • Behavior in case of inconsistency is undefined

summary

  • LuneScript can handle Lua modules.
  • require() and the module declaration are ways to deal with Lua modules.
  • There are restrictions on module declarations.

Next time, we'll talk about macros.