• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

using global Variable in IF-THEN (1 Viewer)

Bobbie

Newcomer
Joined
Nov 17, 2021
Messages
2
Reaction score
0
Standard is a variable a global variable. But when I call a variable in an other "IF-THEN" Statement the variable is NIL.

I give the variable x "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.



Top



How to use a variable in the whole program and not only in the "If then"statement?.

example to determine the variable x

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



Top
 

Bobbie

Newcomer
Joined
Nov 17, 2021
Messages
2
Reaction score
0
"EditMode On"

Code:
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
 

dinsdale247

Moderator
Staff member
Community Patron
Creator of WinLua
Joined
Nov 17, 2020
Messages
93
Reaction score
32
Location
Victoria BC
Website
winlua.net
Hi Bobbie,

The code fails because your variable x is only ever created when the first if statement is true. So if `devicechanged['RemoteWK2'] == "Off"` then the variable x is created when you assign the value 1. If, however `devicechanged['RemoteWK2'] == "On"` then x is never created. The simplest way to fix the problem is to create x outside of the if statements:

Lua:
devicechanged = {}
devicechanged['RemoteWK2'] = 'On'

x = 0 -- Declaring x outside of the if statements will ensure that it exists. 
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
 
Top