functionmoduleluapackagerequire

Is there a difference between global require and local require within a function


AFAIK, once the module has been loaded, lua caches the result into package.loaded[modName]. Does this statement hold true irrespective of where we are doing require "module"?

Following example:

In the below example, script1 just loads the module.lua once so any other usage just fetches the content from package.loaded, whereas script2 requires it twice. In the second case we are loading the module within the function scope, does that mean lua doesn't cache the result of require "module" as to what it does in the first case?

module.lua

local Table = {}
local function print_func(message):
    print(message)
end

Table.print_func = print_func

return Table

script1.lua

local table = require "module"
local function perform()
    table.print_func("PERFORM")
end

local function work()
    table.print_func("WORK")
end

script2.lua

local function do()
    local table = require "module"
    table.print_func("DO")
end

local function work()
    local table = require "module"
    table.print_func("WORK")

Solution

  • There is no difference, other than the result will be discarded in the case of a function, but since the Lua engine will cache the result of "require", when "require" is called next time for the same file, the cached value will be returned. It's an additional table lookup in the latter case and is one of the reasons why global "require" is generally preferred.