Reputation: 177
Please look at the below Lua script.
Idea is, before changing the status, am getting the current status by calling "getStateFlag()" and assigning to "status" variable. Methods ChangeState1 or ChangeState2 can change the current status. So later when calling ResetStatus method I can reset to old status by assigning stored value of "status".
But issue is, this "status" variable always sets to 0.
function Start()
status = 0
local flag = getStateFlag()
if(flag == 1) then
status = getCurrentStatus()
ChangeState1()
else if(flag == 2) then
status = getCurrentStatus()
ChangeState2()
else
ResetStatus(status)
end
end
function ChangeStatus1()
device::set_value(1)
end
function ChangeStatus1()
device::set_value(2)
end
function ResetStatus(status)
device::set_value(status)
end
Upvotes: 1
Views: 659
Reputation: 1891
Based on the comments in Piglet's answer, it sounds like the problem here is that your runtime environment is deleting or clearing your global variables between each run. You could verify that by printing the value of status at the beginning of Start() (assuming you have some way to get output). If it's always nil, that's a pretty good indicator you're losing the global state each time.
If that is the case in your environment, you'll have to find another way to store state across runs. You may have access to a filesystem or some external storage specific to the platform.
Upvotes: 0
Reputation: 28950
So if I understood your question correctly you will call Start()
multiple times.
If flag
equals 1 or 2 you want to store the current status value and then it will be altered inside ChangeState1()
or ChangeState2()
Else you want status
to be reset to the value from your last call to Start()
But currently it will be 0 every time you call Start()
without flag
being 1 or 2.
So basically you only want to initialize status
with 0 when it is not defined yet.
What you can do inside Start() is this:
status = status or 0
So if status
is nil it will default to 0, otherwise it will remain unchanged.
Or you simply initialize status outside the functions.
A cleaner solution would be to separate your backup status from the value that is changed by ChangeState1 or ChangeState2. So you will only access your backupStatus variable when you want to back it up or you want to restore it. otherwise you use some currentStatus variable.
Upvotes: 1
Reputation: 5847
But issue is, this "status" variable always sets to 0.
First of all you should separate two distinct values - previously saved status, and current status you get with getCurrentStatus(). Now you mixed them both in single variable, which gets initialized with 0 every time you enter Start() function. When you're not asking current status (i.e. flag is not 1 or 2), you actually destroy previously saved value with status=0
assignment.
Upvotes: 0