Skip to content

About the 'import' statement #156

@ghost

Description

I've always felt that the import statement was pretty much useless, because the table unpacking syntax does the same job. These are equivalent:

import sub, len, rep from string
{:sub, :len, :rep} = string

Although the syntax is somewhat cleaner, functionally, it's pointless. Maybe instead of unpacking a module, import could act as a helper for requires. In Lua, it's good practice to localize modules in creation and requiring, but this can easily become verbose and tedious:

local module1 = require 'module1'
local module2 = require 'module2'
local module3 = require 'module3'

module1.hello_world()

What I propose is for the import statement to work similarly to that in Python. You would specify a variable name, and the compiler would render a require statement with a string as the variable name.

import module1
import module2
import module3

module1.hello_world!

-- when importing from paths, uses the base of the path
import lib.stuff.morestuff
morestuff.do_things!

In the case that you have a file named differently to what you want to require it as a different name:

-- a player class with lowercase filename
import player as Player

And if you want behavior similar to the old require statement:

import C, Ct, Cmt from lpeg

Which would compile to:

local C, Ct, Cmt
do
  local _req = require 'lpeg'
  C, Ct, Cmt = _req.C, _req.Ct, _req.Cmt
end

The only thing is that it would break compatibility with the current import statement, so at this stage, it might be better to just use a different keyword, such as "requires" or something silly like "needs", "get" or "obtain".

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions