Page 1 of 1

Global or local variable

Posted: Tuesday 16 November 2021 16:27
by Bobbie
Standard is a variable a global variable. But when I call a variable in a "If then" Statement the variable is NIL. Outside the actual "If then" statement I declare the variable x.
How to use a variable in the whole program and not only in the "If then"statement?.

example to determine the variable x

Code: Select all

commandArray = {}
	if  (devicechanged['RemoteWK2'] == "Off")  then
	    print(' Switch is Off')
	    x = 1
	    print(' X = : '  .. x .. ' ');
	end
	
	if  (devicechanged['RemoteWK2'] == "On")  then 
	     print('Switch is On')
	    print(' X = : '  .. x .. ' ');
	end
print(x)
return commandArray
Error code in log: Error: EventSystem: in test-lua: [string "commandArray = {}..."]:12: attempt to concatenate a nil value (global 'x')

Thx

Re: Global or local variable

Posted: Tuesday 16 November 2021 18:48
by jannl
Don't you give the answer yourselves?

Declare the variable before the first if-statement.

Re: Global or local variable

Posted: Wednesday 17 November 2021 0:12
by Bobbie
Thanks for your reply.

I give the variable "1"when the switch is pressed Off ( in the first IF-THEN).
In the second IF-THEN, I call the variable X when the switch is pressed On. --> The error comes with NIL..

Of course I can start before the first IF-THEN with x = 0.
But When x become 1 in the first IF-THEN, after the loop at the end x = 0 again. There is no error.. but x = always 0 now..

I want to see de value of x in the second IF-THEN when I press the On button..

The program is just a sample for testing.

Re: Global or local variable

Posted: Wednesday 17 November 2021 11:33
by jannl
In lua:

Code: Select all

local x
To declare a variable without giving a value. I would suggest to give a value though.

Jan