help on global variables

Hi everyone.

I need to be able to add points to a score.

I have a function that can do that.

I move an image and I get 10 coins, move another now I have 20 coins

All this is good and it works!

I can do this in the file named – page4.lua


Now I want to do the same in a file named – page1.lua

but I need to add 10 more coins to the 20 I already had in page4.lua.

So how do I make a variable that I can call from any file? – page4, page1, or page20

How do the code remember the 20 points I had before?

Do I put that variable name in the main.lua file?

and how?

just the name with no local?

I remember I saw somewhere something about a _G or G_?

Please I need help.

Here’s the link to the Corona SDK external modules tutorial:

http://www.coronalabs.com/blog/2012/08/28/how-external-modules-work-in-corona/

I’m going to read this with more time

to try to understand it. – so far I don’t really get it.

But that is not what I need.

If I have a variable named – imageA = 100

normally I write

local imageA = 100

then I can use imageA in my file.lua


If I want to use imageA, inside of a function, then I have to remove the local

imageA = 100

then I can use imageA, inside the function or another function or ANYWHERE in my file.lua


I need to use the same imageA = 100

in a different file2.lua

or in file7.lua

or in pageBackUp.lua


So the question is how do I write the variable, to use it in all my files.lua?

Hi Victor,

We strongly discourage the use of global variables, especially since there are simple and clever ways to avoid them. Please read this tutorial on the matter:

http://www.coronalabs.com/blog/2013/05/28/tutorial-goodbye-globals/

Brent

An external module is exactly what you need.  It will persist between pages as long as you don’t specifically get rid of it.  I use them all the time.

Create  globaldata.lua

[lua]

local this = {}

this.someDataToKeep = nil

return this

[/lua]

In page1.lua

[lua]

local globaldata = require( “globaldata” )

globaldata.someDataToKeep = 9999

[/lua]

In page#.lua

[lua]

local globaldata = require( “globaldata” )

local savedPoints = globaldata.someDataToKeep

[/lua]

Cheers.

still confuse…

Tell me if I’m thinking the correct thing.

I have to create another file (module) like – myData.lua

Do I have to put all this in the file?

display.setStatusBar( display.HiddenStatusBar ) local storyboard = require "storyboard" storyboard.purgeOnSceneChange = true storyboard.gotoScene( "home" )

or this

local storyboard = require( "storyboard" ) local scene = storyboard.newScene()

or nothing…

Then do I have to write this?

--my global space local M = {} return M

If so then I write the variables or the functions under…

--my global space local M = {} return M local scoreObject local score = 0 local glow local function addToScore(num)     score = score + num     scoreObject.text = score end local function resetScore ( )     score = 0     addToScore(0) end

or I have to remove the local like this:

--my global space M = {} return M scoreObject score = 0 glow function addToScore(num)     score = score + num     scoreObject.text = score end function resetScore ( )     score = 0     addToScore(0) end

And then I can use the addToScore function in any other file.lua

is that more or less correct?

All wrong, so slowly :slight_smile:

First I would recommend you to read about variables scope in Lua :slight_smile:

But shortly:
If you write [lua] local var[/lua] but not in function (scopes), Lua will create variable accessable in whole file it was declared.
If you ommit’local’ it will create variable in space (called global) which is accessable wherever in program, however it is strongly discouraged as it’s not efficient and pollutes code.

If you want to expose content of file outside, you must use ‘return’ keyword (as in function). However it is better ( if you have a lot of variables and functions) to wrap it into something as table.

So at the top of the file we create table with
[lua] local t = {} [/lua]

Next we create variable we want to expose, but we declare it as table key
[lua] t.glow = 5 [/lua] (in lua you can also asign function this way, as t.func = function() end)

At the end of file we must return our ‘t’

In other file if we do [lua] local lib = require (“name of the file with table t”) [/lua], returned table ‘t’ from file will be assigned to variable ‘lib’ (as you would call function and assign value returned by it)

Now under variable ‘lib’ you have reference to table in other file so you can do [lua] local a = lib.glow * 5 [/lua], you can also modify it, because ‘lib’ is now reference to ‘t’ not just copy (tables always are passed by references)

If you would write [lua] local glow [/lua] in file with ‘t’ but wouldn’t make it part of returned table ‘t’, lib.glow would return empty nil because it wasn’t part of returned table :slight_smile:

Hi develephant. adn Brent, and everyone else

– I know this post it’s long. Please read it, it’s important to understand. —

Thanks for the post. I’m Trying to understand this new concept. it’s hard…

I did just like you told me, word by word

–create a new file globaldata.lua

–inside I created the table you said – this {}

–then I put the .someDataToKeep to the table     – I put the file inside the folder, where I have the main.lua file.


Then in page1 – for me it’s the very first page that I see, main.lua is sending me to this page first.

this page I have the name of home.lua


In home.lua I put this

local storyboard = require( "storyboard" ) local widget = require "widget" local scene = storyboard.newScene() local globaldata = require( "globaldata" )    globaldata.someDataToKeep = 9999

So I requiere the globaldata and add a number to the someDataToKeep.


Then in another page… page1 I tried this.

–I requiere the globaldata again…

and put this

local savePoints = globaldata.someDataToKeep local function letsSee () print(savePoints) end letsSee()

To see if it works…

I run the program, and in the console it writes

9999

So it works!


But I still have the same problem with the scores, I don’t really get how to make the scores work.

I ask you please, to be patience with me, I’m doing my best.


In pageR I have a score function and variables that make the score works

–I got this from the videos I bought from Jay White. – the ones they have in Corona.

scoreObject score = ud.someData local glowCoin function addToScore(num)     score = score + num     scoreObject.text = score end function resetScore ( )     score = 0     addToScore(0) end [code]   So inside a function a use the call addToScore(10)   [code] if plant.x == 670 then             transition.to(plant, {time=100, x=670, y=406})             plant:removeEventListener ("touch", plantTouch)             audio.play(win)             coinPlanta.isVisible = true             transition.to(coinPlanta, {time=1000, x=glowCoin.x, y=40, onComplete=glow})             addToScore(10)         end

And it adds 10 points to the scoreObject – this is perfect.

But when I go to another page … page1 or page4 or page6

I don’t know what to do to “keep adding points”

If I put the call addToScore(20) – the program tells me is a “nil” value

because the addToScore it’s not there.

But If I do the same thing that I did in pageR

then it resets to 0 and adss only the 20 new points, so it’s not adding more extra points.


When you know how to do things it’s really simple

but right now I’m just going crazy.

Please help me out

Hi piotrz55.

I’m trying to understand.

You make it sound simple.

but my head and my brain are not that advanced yet!, sorry!

Please read the above post, to see if you can explain things in

a little bit different way, to help me understand.

I think I can understand it, I just need to make my brain get it.

I think with your help, form all of you.

I will get this new challenge.

Thanks for your patience!

If it’s hard, lets break it down :slight_smile:
First I suggest you leave storyboard and widgets for now because it’ll make it somehow harder to understand overall.

Ask step by step what isn’t clear and we’ll try to solve it, even if it’s the most basic one. If still not clear, I’ll try to rephrase again :slight_smile:

But must know your programming experience if any (mainly languages)

okay…step by step…I like that.

I have a folder.

inside that folder I have the main.lua file to start the app.

I have the requiere storyboard in main.lua and that takes me to home.lua – another file/module

In there I have 3 variables to add score or points.

– scoreLabel – where I have the image of the word “score”

– scoreObject – here is a number “0” it’s an object that changes as it gets more points.

– score = 0 – this is a variable named score and that has 0 points

in the same home.lua file I have right under those 3 variables, 1 functions

function addToScore(num)     score = score + num     scoreObject.text = score end

This function is to pass a number

so when I call the function to run…

I use this command…

addToScore (  ) – but Inside the parenthesis I add the points I want to give to the player, like this:

addToScore(10)

the function I use is this

if plant.x == 670 then             transition.to(plant, {time=100, x=670, y=406})             plant:removeEventListener ("touch", plantTouch)             audio.play(win)             coinPlanta.isVisible = true             transition.to(coinPlanta, {time=1000, x=glowCoin.x, y=40, onComplete=glow})             addToScore(10)         end

And it works, it adds 10 points and in the variable … I see now 10, where before was a 0

So far so good.


All I need, it’s to be able to go to another file/module, not home.lua

let’s say page2.lu, and call the addToScore (20) function and add the points

10 in the home.lua plus 20 in the page2.lua

and I will have 30 points in the scoreObject.


I need the storyboard because I have many files in my app.


The problem is when I go to page2.lua and call addToScore

it gives me a nil value.

because page2 does not have the function name “addToScore”

so that’s why I get nil

I hope this will explain things a little bit better.


Programming experience – not much.

I have 2 apps in the app store already, they are very simple apps

but very nice. Actually I have sold about 300 of one of them

“Piano For Kids Level 1”

For me 300 it’s a lot, I’m very happy.


That’s why I want to learn more

so I can make better apps

Right now I just want to be able to add points to the score

all the games have that, I thought, it was not going to be too hard

but it seems it is really difficult.

Thanks for your help.

No, no - wait. As I said, leave storyboard for now. We must first resolve concept of making modules and variable scopes :slight_smile:

Okay…

You tell me what to do

I do want to learn

Just leaving storyboard will be enough :smiley: :smiley:

Let’s strip your main to empty file and create globaldata.lua

in globaldata write

[lua]

local dataTable = {}

– place for some code here

return dataTable

[/lua]

and in main write 

[lua]

local myExternalData = require( “globaldata” )

[/lua]

everything in one folder

Let’s see what happened. When Corona starts it always executes main.lua and main.lua only - it’s important.

If you want to get content from other file you must load it’s content somehow.

When you written 

[lua]

local stroyboard = require(“storyboard”)

[/lua]

you have done exacly the same as we’ve done with local myExternalData = require( “globaldata” ) line :slight_smile:

require() function loads file’s code into memory and returns data if any - as in function, if we want something to be returned, we use ‘return’ at the end. In storyboard case it return table with bunch of functions. We also returned table, but for now empty.

Is it somehow clear up to this point?

Okay…

globaldata.lua is a file. (it’s the state of Florida)

I have another file – main.lua (it is the state of California)

They are 2 different files.

I just run the app and it was “black”

because in main.lua there is nothing!


Then I add this line – inside the table

in the globaldata.lua file

local background = display.newImage (“backgroundGrass.png”)


and I add the require line for the globaldata in main.lua


And when I run the program I saw the image of the Grass, the background



I think I get it.

Here I create a table

local dataTable = {}

A make an empty box. There is nothing in there right?

what exactly does the “return”

return dataTable

is it, like saying…

Let me know what’s inside the box?

How inside table? :smiley:

And it isn’t example, becaue you show image on screen from globaldata.lua, but you have no means to access it in main.lua

‘return’ is as in function

[lua]

local function AddTwo( number )

     return number + 2

end

local var1 = AddTwo(5)

local var2 = addTwo(18)

[/lua]

so I after I have done require(), myExternalData equals dataTable from globaldata.lua

If you say that after 

[lua]

local myTable = {}

local background = display.newImage( … )

[/lua]

background is in table, then no! How so? You just created table and image, two separate things :stuck_out_tongue:

When you require() file, then if it wasn’t already required earlier, all it’s code is executed first. That’s the reason there is something on the screen. Then require returns (as function) valiables you preceded with return in globaldata.lua. In other files, lua will see that it already exexuted file so than it will only return valiables.