Hi Rob, I finally got around to read your blog post. I really appreciate you sharing it with us. There were a couple of things I wasn’t quite sure, which you helped to clarify for me:
-
Use of _G. It sounds like _G is provided by Lua to help coders/programmers to remember what is declared as global and what isn’t (meaning, if it’s not _G.myVariable, then it should be declared local the first time the variable is introduced). I avoided using _G because I didn’t have a feel for it, and I’d rather use what I know I’m using. So, in place of _G, I declared one variable global (say, for example, myGlobal, which is a table), and use it in place of _G. I suppose it’s okay, but is there a reason why I should replace myGlobal with _G?
-
Use of local. I think I missread somewhere that if I declare a variable local and then declare it to be local again, it turns into a global variable. Your blog post completely eradicated my misconception. It will definitely make it easier for me to declare things local. I love this. I was taking trouble creating different names for each local variable, and double/tripple check to make sure local isn’t infront of the variable more than once in each lua module. Now, I can safely use same name with local in front of it without too much worries, so long as they are not inside the same namespace.
Now, I have a couple of questions.
Q1) I’m thinking that once a project is launched, until I exit the project, main.lua is never unrequired, and therefore, it’s in memory. Would that make local variables in main.lua accessible to other lua module, especially when other modules use module(…, package.seeall);? From what you wrote, I now think that all variables declared as local in main.lua are only available in main.lua. Even if other module can see main.lua, that doesn’t make what’s local to main.lua accessible to the other module. Just wanted to make sure I understood this.
Q2) I’ve been puzzling over why would anyone do something like:
[lua]local director = require(“director”);[/lua]
I use director class, and it is needed in every lua scene. I don’t understand why I would want to declare it as local in main.lua (and if I do, I would need to require director locally in every lua scene I load). What I decided was to require classes that I know I’d use almost everywhere as global. So, my main.lua requires classes like this:
[lua]-- require as global
diretor = require(“director”);
ui = require(“ui”);
loqsprite = require(“loq_sprite”);
loq_util = require(“loq_util”);
json = require(“json”);
physics = require(“physics”);
store = require(“store”); – not needed everywhere, but I think it needs to be global in my case[/lua]
Is it better to require them as local (except the “store” I suppose), and require them in each module that I need them? If it is better to do so, what might be the reason? Why should I not require them as global?
Thanks again for helping people new to programming!
[import]uid: 67217 topic_id: 16401 reply_id: 61615[/import]