tech

[English] [Japanese]

26. subfile

As the processing of the module grows, the file grows accordingly.

A bloated file is not a good thing, so in such a case the common refactoring is to subdivide the responsibilities of the modules and separate the files for each module.

However, there are many cases where the responsibilities cannot be divided cleanly, or the influence on other modules becomes large when the responsibilities are divided. Subfiles are used as an alternative when module division is not possible.

A subfile is to divide a module, which originally consisted of one file, into multiple files.

LuneScript is in principle 1 module = 1 file, but when subfiled, 1 module = multiple files.

Subfile structure

A subfile consists of one main and multiple subs.

- main
  +- sub1
  +- sub2
  +- ...
  +- ...
  +- subN

how to use

If main.lns and sub.lns exist under the foo/bar directory as follows and sub.lns is a subfile of main.lns,

foo/bar
     + main.lns
     + sub.lns

To use subfiles, declare them in main as follows:

// @lnsFront: skip
subfile use foo.bar.sub;

On the subfile side, declare as follows.

// @lnsFront: skip
subfile owner foo.bar.main;

This will treat the specified module (foo.bar.sub in the example above) as a separate subfile, and sub.lns as part of the main.lns module.

limit

The module declaration should be done at the top of the script. However, comments are excluded.

Multiple subfile use can be declared in one file. Only one subfile owner can be declared. In other words, one file can have multiple subfiles, but one subfile can only be used by one owner.

If multiple subfile use declarations are made, the subfiles are processed in the order in which they are declared.

Subfiles are basically the same as #include in C, but differ from #include in the following points.

  • #include in C expands the file where it is declared, but LuneScript expands the subfile at the end of the file.
  • The subfile must end as a statement.

    • Part of an expression, like #include, cannot be written in a subfile.
  • There must be one main file to subfiles.
  • You cannot use subfiles from subfiles.

For example, if you have the following main.lns, sub1.lns, sub2.lns,

  • main.lns
// @lnsFront: skip
//------ main.lns -------
subfile use sub1;
subfile use sub2;

pub let val = 1;
  • sub1.lns
// @lnsFront: skip
//------ sub1.lns -------
subfile owner main;

pub let val1 = 1;
  • sub2.lns
// @lnsFront: skip
//------ sub2.lns -------
subfile owner main;

pub let val2 = 1;

main.lns is equivalent to the following script.

// @lnsFront: skip
//------ main.lns -------
pub let val = 1;
pub let val1 = 1;
pub let val2 = 1;