lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2018-02-24 15:28 GMT+02:00 albertmcchan <albertmcchan@yahoo.com>:
>
>
> On Feb 24, 2018, at 7:46 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>
>> Actually, the manual documents what 'require' does, in particular:
>>
>> "Once a loader is found, require calls the loader with two arguments:
>> modname and an extra value dependent on how it got the loader. (If the
>> loader came from a file, this extra value is the file name.)"
>>
>> And dofile does not do that.
>>
>> Thanks.
>>
>> -- Dirk
>>
>
> does require cache the result, and set package.loaded.mod ?
> If mod were "required", BEFORE mod.lua return results to set
> package.loaded.mod, require function set it to something not nil

On entry to mod.lua, package.loaded.mod must be nil if the package is
being required. The file would not be loaded otherwise.

> AFTER the require call, package.loaded.mod is set to whatever
> mod.lua returns (or true if mod return nothing)
>
> --> with require(), package.loaded.mod always tested not nil
>
> if package.loaded.mod then
>   -- loaded from require
> else
>   -- run as a program
> end

I have settled on the following version as conforming to the docs, i.e. safest:

local modname, filename = ...
if filename and filename:match(modname .."%.lua$") then return end

This code can be cut-and-pasted since it does not depend on the module
name. It even works for submodules, e.g.
    require "mod.submod"

The only caveat is that the module name must not contain a magic
character except "."; in particular (I burnt my fingers on this one)
not a hyphen.