Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 467
Timmmm Avatar asked Apr 24 '16 09:04

Timmmm


People also ask

Why do we use local in Lua?

Local variables help you avoid cluttering the global environment with unnecessary names. Moreover, the access to local variables is faster than to global ones. Lua handles local variable declarations as statements. As such, you can write local declarations anywhere you can write a statement.

What does local mean in Lua?

When we store a function into a local variable we get a local function, that is, a function that is restricted to a given scope. Such definitions are particularly useful for packages: Because Lua handles each chunk as a function, a chunk may declare local functions, which are visible only inside the chunk.

What does require () do in Lua?

Lua offers a higher-level function to load and run libraries, called require . Roughly, require does the same job as dofile , but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work.

Do you need to declare variables in Lua?

In lua, there is no need to declare or initialize variables before they are used. By default, variables are initialized to the value of nil.


1 Answers

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.

like image 131
Diego Pino Avatar answered Oct 01 '22 16:10

Diego Pino