In Lua how do you import modules?

Vitaly picture Vitaly · Aug 30, 2011 · Viewed 51.8k times · Source

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.

Answer

Nicol Bolas picture Nicol Bolas · Aug 31, 2011

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