Global or local variable

Moderator: leecollings

Post Reply
Bobbie
Posts: 4
Joined: Friday 26 August 2016 15:03
Target OS: Linux
Domoticz version:
Contact:

Global or local variable

Post 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
Last edited by Bobbie on Wednesday 17 November 2021 17:03, edited 1 time in total.
jannl
Posts: 673
Joined: Thursday 02 October 2014 6:36
Target OS: Raspberry Pi / ODroid
Domoticz version: 2022.2
Location: Geleen
Contact:

Re: Global or local variable

Post by jannl »

Don't you give the answer yourselves?

Declare the variable before the first if-statement.
Bobbie
Posts: 4
Joined: Friday 26 August 2016 15:03
Target OS: Linux
Domoticz version:
Contact:

Re: Global or local variable

Post 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.
Last edited by Bobbie on Wednesday 17 November 2021 12:45, edited 1 time in total.
jannl
Posts: 673
Joined: Thursday 02 October 2014 6:36
Target OS: Raspberry Pi / ODroid
Domoticz version: 2022.2
Location: Geleen
Contact:

Re: Global or local variable

Post 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
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest