Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lua how do you import modules?

Do you use

require "name"

or

local name = require "name"

Also, do you explicitly declare system modules as local variables? E.g.

local io = require "io"

Please explain your choice.

Programming in Lua 2ed says "if she prefers to use a shorter name for a module, she can set a local name for it" and nothing about local m = require "mod" being faster than require "mod". If there's no difference I'd rather use the cleaner require "mod" declaration and wouldn't bother writing declarations for pre-loaded system modules.

like image 496
Vitaly Avatar asked Aug 30 '11 19:08

Vitaly


People also ask

How do I import a module into Lua?

Now, in order to access this Lua module in another file, say, moduletutorial. lua, you need to use the following code segment. In order to run this code, we need to place the two Lua files in the same directory or alternatively, you can place the module file in the package path and it needs additional setup.

Where does Lua look for modules?

And Lua will now search for modules in the lib directory (in addition to where it usually does). You can also use the LUA_PATH environment variable to do this before even starting Lua.

What is Lua library?

A Lua library is a chunk that defines several Lua functions and stores them in appropriate places, typically as entries in a table. A C library for Lua mimics this behavior. Besides the definition of its C functions, it must also define a special function that corresponds to the main chunk of a Lua library.

How do I create a function in Lua?

In Lua, we declare functions with the help of the function keyword and then, we can invoke(call) the functions just by writing a pair of parentheses followed by the functions name.


1 Answers

Either of them works. Storing it in a local will not change the fact that the module may have registered global functions.

like image 60
Nicol Bolas Avatar answered Oct 12 '22 01:10

Nicol Bolas