1989
1989

Reputation: 19

When one should use local and global functions and variables in corona sdk?

If there are more than one file(main.lua) which contains code and I declare some variables and functions global. Are these variables and functions global in all files or can I access them through any file? And also is there any problem if I use only global variables and functions? I am using director class

Upvotes: 1

Views: 3766

Answers (4)

Juan Fco. Roco
Juan Fco. Roco

Reputation: 1638

Read this (the official Corona Labs recommendation):

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

Basically, they recommend:

  • Do not use global vars

  • If you want to access vars between modules, do the following

Create a new module to store "across-modules" vars.

mydata.lua

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

Use the module inside other modules:

In main.lua

local myData = require( "mydata" )
myData.myVariable = 10
director:changeScene("other")

In other.lua

local myData = require( "mydata" )
print(myData.myVariable)

Result: 10

Hope this helps.

Upvotes: 2

ryosua
ryosua

Reputation: 65

Using Director, I think if you declare variables global in the main.lua file, you can access them anywhere, but if you declare them global in a module/scene they are not accessible anywhere else. Try to use local variables whenever possible, use globals only if it is necessary to use them.

Upvotes: 0

Mike Corcoran
Mike Corcoran

Reputation: 14564

if you have multiple lua files, and they need to be able to use information from one another - you should use lua's module system. this is what it was designed for.

you can read the documentation here: http://www.lua.org/manual/5.1/manual.html#5.3

Upvotes: -1

jpjacobs
jpjacobs

Reputation: 9559

Globals are not bad by definition, but in general you should only use them when you really need to share data.

Otherwise you will end up with pieces of code which should not interact, but do share a variable in an unexpected way ( think temporary variables etc etc).

The best approach is to declare everything local unless you absolutely must share the variable.

Upvotes: 6

Related Questions