Some libraries work only one way, and some only work the other way
The require "name"
syntax was the one introduced in lua 5.1; as a note; this call does not always return the module; but it was expected a global would be created with the name of the library (so, you now have a _G.name
to use the library with). eg, earlier versions of gsl-if you did local draw = require"draw"
the local draw
would contain true
; and shadow the global draw
created by the library.
The behaviour above is encouraged by the module
function ==> now relatively deprecated, any well written new code will not use it.
The local name = require"name"
syntax became preferred recently (about 2008?); when it was decided that modules setting any globals for you was a bad thing.
As a point: all my libraries do not set globals, and just return a table of functions; or in some other cases, they return an function that works as an initialiser for the root object.
tldr;
In new code, you should use the latter local name = require"name"
syntax; it works in the vast majority of cases, but if you're working with some older modules, they may not support it, and you'll have to just use require"module"
.
To answer your added question:
do you require the system modules?: no; you just assume they are already required; but I do localise all functions I use (usually grouped into lines by the module they came from), including those from external libraries. This allows you to easily see which functions your code actually relies on; as well as removing all GETGLOBALs from your bytecode.
Edit: localising functions is now discouraged. To find accidental globals use a linter like luacheck
Sample module in (my) preferred style; will only work with the local name = require"name"
syntax.
local my_lib = require"my_lib"
local function foo()
print("foo")
end
local function bar()
print("bar", my_lib.new())
end
return {
foo = foo;
bar = bar;
}