Need help with scope of variables

I'm sorry if this isn't the right forum to ask this in, but I'm new, just let me know.

In my main() function I do a:

require ("external")

In this file I declare a local ball_1 that is a physics object in a group.

Back in my main() function, I cannot seem to access ball_1.x

Is there something I need to do so that the ball_1 object is accessible everywhere in my code?

try using _G.ball_1 :)

@selticesystems,

I will write an article on scope of variables, but till then a quick explanation.

Do you know what a "scope" is? for the benefit of others, I will just re-iterate that. The scope of a variable indicates the reach and lifetime of a variable. So a local variable is available to that function/module only.

Now when you declare your ball_1 as local in the external.lua, it will be available *only* to that file not to any other file, even if you use require. To make this available to others, you need to *not* make it local. Easy as that.

I would avoid playing with the _G. Think of the _G as, I can write code in Assembly to make the system do what I want, but would I use assembly code or would I use C/C++/Lua code? The correct answer is "as circumstances dictate". But generally, as a rule of thumb, I would avoid all assembly code.

cheers,

?:)

I do understand what the Scope of a variable is, I'm a proficient programmer in other languages, and I'm new to Lua.

Here is a situation similar to what I'm dealing with:

1) In main.lua I have a function called createLevel() that requires an external file called ext.lua

2) In ext.lua I create the physical level and one call is as follows:

local ball_1 = display.newImage(...)

3) Now, back in createLevel() in the main.lua I try to access ball_1.x and it's as if it doesn't exist.

I'd like to take the level creation code out of my main.lua and put it in an external file, but it appears that using "require" and defining variables in that file doesn't work, because the scope of the variables inside that file don't seem to reach the calling file/script.

Mostly, the purpose of what I'm doing is that I want separate .lua files for each of my world level creation scripts and an easy way to include them.

I need to do some reading on Lua it appears.

just a quick question, understandable that you want to make your levels in separate files, then why would you want to have floating variables. Why do you not create a structure or a class and have the ball_1 as a member of that.

1
2
3
4
5
6
7
8
9
10
--
--
-- main.lua
--
--
 
local level = require("level1").load()
 
local balls = level.getNumOfBalls()
local ball_1 = level.getObject(1)
views:1614 update:2011/9/26 15:43:22
corona forums © 2003-2011