Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lua optimize duplicate imports?

Tags:

import

lua

In simple model I have 3 files:

base-module.lua
module-one.lua
module-two.lua

And this is my import connections:

module-two.lua < --|
     ^             |
     |             |
     |             |  
module-one.lua     |
     ^             |
     |             |
     |             |
base-module.lua ----

module-one.lua import base-module.lua and so on.... When I remove base-module.lua import from module-two.lua I see all functions and variables from base-module.lua but my imports is not inventive. Does lua optimize double import like it make pytho for example?

like image 970
itdxer Avatar asked Nov 27 '13 12:11

itdxer


Video Answer


2 Answers

Yes, Lua does.

As manual on require in section 5.3 says:

Loads the given module. The function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname].

like image 132
Oleg V. Volkov Avatar answered Nov 05 '22 21:11

Oleg V. Volkov


Short answer, yes.

Long answer:

require (modname)

Loads the given module. The function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module.

To find a loader, require is guided by the package.loaders array. By changing this array, we can change how require looks for a module. The following explanation is based on the default configuration for package.loaders.

First require queries package.preload[modname]. If it has a value, this value (which should be a function) is the loader. Otherwise require searches for a Lua loader using the path stored in package.path. If that also fails, it searches for a C loader using the path stored in package.cpath. If that also fails, it tries an all-in-one loader (see package.loaders).

Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value to package.loaded[modname]. If the loader returns no value and has not assigned any value to package.loaded[modname], then require assigns true to this entry. In any case, require returns the final value of package.loaded[modname].

If there is any error loading or running the module, or if it cannot find any loader for the module, then require signals an error.

like image 25
Etan Reisner Avatar answered Nov 05 '22 21:11

Etan Reisner