Local variables position

Hi there,

I have a lot of experience coding however sometimes my variable is not being read.

If I put a variable at the top it should be able to be read in functions. However, it is not working my sample code looks like this.

1
2
3
4
5
6
7
local myCoolVariable
 
local function myCoolFunction (event)
 
myCoolVariable = myCoolVariable +1
 
end

I don't have lots of experience coding, but maybe this may make a difference?

1
2
3
4
local myCoolVariable = 0
local function myCoolFunction (event)
        myCoolVariable = myCoolVariable + 1
 end

Naomi's first suggestion will work, you need to declare it's a variable or table. If you don't, while the program will know that it exists, it won't know what it is/what to do with it.

Hi guys,

Thank you for the response. I have solved the problem initially I wanted my variable to tell if the player was walking and then that would play the animation.

Corona handles things a little differently. Anyway problem solved!

Thanks again.

an addition to the issue as to why it will work or not work,

when you just use

local myVariable

it has the value of 'nil'

and when you perform myVariable = myVariable + 1

you are essentially adding nil + 1 which results in an error, so it will *not* work

so by just initialising the variable with a numeric value, you are ensuring that the maths works and so does your app/code.

Addenum: it will be unfair to say that Corona works differently, it is not Corona, it is the fact that in other languages, you explicitly define the variable type, so the default value of 0 is assigned to the variable. However since Lua is dynamic and flexible, it requires you to set the default value as it will allow

myVariable = {}
myVariable = "0"
and myVariable = 0

cheers,

?:)

Ah, that makes a real good sense, Jayant. Thanks for the explanation!

Naomi

views:1194 update:2011/10/29 17:13:10
corona forums © 2003-2011