Why use local requirements in Lua?

What is the difference between this

local audio = require "audio" 

and

 require "audio" 

Are there any advantages in the first?

+6
source share
1 answer

In Lua, a module is an object that exports several public functions. There are two ways to define 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 first is the old way of defining a module, but it can still be found in many examples. The latter is the preferred way to define modules.

So, if you do not assign a module to a local variable, there is no way to refer to its exported variables and methods.

If audio defined any global functions, these functions will be available after importing audio . Global functions and variables are bound to a global object. In Lua, there is a variable called _G that contains all the global variables and functions. For instance,

audio.lua

 function play() print("play") end 

main.lua

 require("audio") play() 

or

 require("audio") _G.play() 

This works, but putting everything in a global object has several inconveniences. Variables and functions can be overwritten. Ultimately, the global object becomes and swells. It's best to structure everything in modules, so variables and methods are encapsulated in their own namespace.

+5
source

All Articles