Timmmm
Timmmm

Reputation: 96625

Why use local require in Lua?

What's the difference between this

local audio = require "audio"

and

require "audio"

Is there any advantage of the former?

Upvotes: 10

Views: 6128

Answers (1)

Diego Pino
Diego Pino

Reputation: 11586

In Lua a module is an object that exports several public functions. There are two ways of defining a module in Lua. For instance:

module(..., package.seeall)

Audio = {}

function Audio:play()
   print("play")
end

Or alternatively:

Audio = {}

function Audio:play()
   print("play")
end

return Audio

The former is the old way of defining a module, but it's still can be found in many examples. The latter is the preferred way of defining modules now.

So, unless you assign a module to a local variable there's no way of referencing its exported variables and methods.

If audio had defined any global functions, those functions would be available once audio is imported. Global functions and variables are attached to the global object. In Lua there's a variable called _G which contains all global variables and functions defined. For instance,

audio.lua

function play()
   print("play")
end

main.lua

require("audio")

play()

Or

require("audio")

_G.play()

That works, but putting everything in the global object has several inconveniences. Variables and functions may be overwritten. Eventually the global object becomes and bloated. It's better to structure everything in modules, so variables and methods are encapsulated in their own namespace.

Upvotes: 9

Related Questions