Importing modules. How you do this?

I always do it like this

require "ads"

but in many examples it is done like this

local ads = require "ads"

Does it matter?

the first statement just includes everything inside the file ads.lua to the calling file. 2nd statement create a variable for the added module if using the local keyword it creates a local instance of the added module. access to the function and properties inside the added module will be faster using the second statement.

Thanks, renvis. So when you use the first statement it just creates a global variable named "ads" and if you use the second statement it also creates a local variable "ads" that overrides the global "ads" and gives faster access to its variables?

I'm going to refactor all my import declarations and see if there's any real world difference, but I guess it's more of a good programming practice.

first statement won't create any variable. to create global variable you should be using
 var = require("ads")

Hmm... but whether I use the first of second statement, further usage is exactly the same, like ads.init() for example.

EDIT: also, I call functions from system modules like "display" without prior explicit declaration. I guess, I should do
local display = require "display" as well?

a lot of Corona's API's are there for you without doing a require. Almost any app we are going to build needs the display API, so it makes sense to have it always around.

But not every program is going to use the JSON library, or the ads API, so those optional ones are not loaded by default to keep your app size down and you have to specifically load them with the require statement.

ads = require("ads")

loads the ads API into the global space of the application.

local ads = require("ads")

loads the ads API into the local scope.

views:1637 update:2011/9/26 15:43:22
corona forums © 2003-2011