Page 1 of 1

Attempt to perform arithmetic on global 'xx' (a nil value) Error

Posted: Monday 13 May 2019 17:45
by quiggles
I have this code that is tracking the time that a door is open, (FrontDoorOpenMins is a global variable set as an integer with an initial value of 0):-

Code: Select all

return {
	on = {
		timer = {'Every minute'},
	},

    execute = function(domoticz)
        local fD = domoticz.devices('Front Door')

	    if (fD.state == 'Alarm') then -- state == 'On'
	        local x = FrontDoorOpenMins + 1
	        
            domoticz.variables('FrontDoorOpenMins').set(x)
		    domoticz.notify('Front Door open ' .. FrontDoorOpenMins .. ' ### ')
		    domoticz.log('Front Door open ' .. FrontDoorOpenMins .. ' ### ')
		else
		    domoticz.log('Front Door not open ')
            domoticz.variables('FrontDoorOpenMins').set(0)
	    end
	end  
	
But I get this error and don't understand why. Instead of the temporary variable x I tried a direct "FrontDoorOpenMins + 1", but that doesn't work either.

Code: Select all

2019-05-13 16:38:00.541 Status: dzVents: Info: ------ Start internal script: FrontDoor:, trigger: every minute
2019-05-13 16:38:00.559 Status: dzVents: Error (2.4.18): An error occured when calling event handler FrontDoor
2019-05-13 16:38:00.559 Status: dzVents: Error (2.4.18): ...Domoticz\scripts\dzVents\generated_scripts/FrontDoor.lua:12: attempt to perform arithmetic on global 'FrontDoorOpenMins' (a nil value)
2019-05-13 16:38:00.559 Status: dzVents: Info: ------ Finished FrontDoor

Re: Attempt to perform arithmetic on global 'xx' (a nil value) Error  [SOLVED]

Posted: Monday 13 May 2019 18:16
by waaren
quiggles wrote: Monday 13 May 2019 17:45 I have this code that is tracking the time that a door is open, (FrontDoorOpenMins is a global variable set as an integer with an initial value of 0):-
But I get "attempt to perform arithmetic on a nil value" and don't understand why.
You try to access the Lua variable before it is set with a value. Until it is set, it is still nil.
Try this

Code: Select all

return {
    on = {
        timer = {'Every minute'},
    },

    execute = function(domoticz)
        local fD = domoticz.devices('Front Door')
        local frontdoorOpenMinutes = domoticz.variables('FrontDoorOpenMins')
        
        if (fD.state == 'Alarm') then -- state == 'On'
            local x = frontdoorOpenMinutes.value + 1
            local strX = tostring(x)  
            
            frontdoorOpenMinutes.set(x)
            domoticz.notify('Front Door open ' .. strX .. ' ### ')
            domoticz.log('Front Door open ' .. strX .. ' ### ')
        else
            domoticz.log('Front Door not open ')
            frontdoorOpenMinutes.set(0)
        end
    end  
}

Re: Attempt to perform arithmetic on global 'xx' (a nil value) Error

Posted: Monday 13 May 2019 20:12
by quiggles
AH! Thankyou! Didn't understand the relationship between the variable types.

Cheers!