difference between ‘local Class = require("Class")’ and ‘require "Class"’?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
randy0428
Citizen
Posts: 51
Joined: Sun Jul 31, 2016 10:19 am

difference between ‘local Class = require("Class")’ and ‘require "Class"’?

Post by randy0428 »

I've successfully created some basic games, so in my learning I'm now focusing more on details, refining and writing better, more efficient code.

This may seem like a stupid question, but what's the difference between ‘local x = require("some_file")’ and ‘require "some_file"’ and when should I use one instead of the other? My initial thought is that it's probably better to always use ‘local x = require("some_file")' and never ‘require "some_file"’? But I'm not sure.
User avatar
Ulydev
Party member
Posts: 445
Joined: Mon Nov 10, 2014 10:46 pm
Location: Paris
Contact:

Re: difference between ‘local Class = require("Class")’ and ‘require "Class"’?

Post by Ulydev »

It all depends on how your module is organized.
You could either have a file returning something (

Code: Select all

return myLibrary
), in which case you’ll use

Code: Select all

local myLibrary = require ...
or directly injecting into the global scope (

Code: Select all

myLibrary = ...
), then require it directly.

Indeed, the best practice is to use local variables to avoid polluting the global scope and prevent conflicts from multiple modules.
With small scale projects, it should not matter though. I find it less redundant to just require all modules at once in main.lua then be able to use them in all other files.
User avatar
ReFreezed
Party member
Posts: 612
Joined: Sun Oct 25, 2015 11:32 pm
Location: Sweden
Contact:

Re: difference between ‘local Class = require("Class")’ and ‘require "Class"’?

Post by ReFreezed »

To add to what Ulydev said: the module itself shouldn't add globals if it's supposed to be like a library, but you can add the library as a global elsewhere:

Code: Select all

-- In main.lua, or somewhere else appropriate.
_G.myLib = require("myLibrary")
_G.otherLib = require("myOtherLibrary")
That way the library won't pollute the global space by default, but you do have the choice of conveniently having the library accessible as a global in your game.

If the module is not like a library then it's all up to the purpose of the module. I usually have several files that just adds a bunch of miscellaneous global functions/constants/values in my programs. Other modules just contain a big ol' table of data (i.e. does not add any globals).
Tools: Hot Particles, LuaPreprocess, InputField, (more) Games: Momento Temporis
"If each mistake being made is a new one, then progress is being made."
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest