Object-oriented get/set of Luup device variables

I don’t know about you, but I get pretty fed up with writing:

x = luup.variable_get (serviceID, variableName, deviceNo)

or

luup.variable_set (serviceID, variableName, value, deviceNo)

Maybe I’m just lazy, but it’s prone to mistakes and gets messy when spread throughout a program.
Of course, you can just write get/set functions for specific variables or devices, but that’s a bit messy too.

What I’ve found useful is to create objects (using a constructor named [tt]Variable[/tt] here) with a get/set method for any of the device variables I’ll be using (and declare them at the start of the chunk of code). For example:

a =  Variable (serviceID, variableName, deviceNo)

So you can thereafter simply write, for example:

b = a.get()
a.set(value)

The constructor code I use is this:

function Variable (service, variable, device)
	return {
		get = function (   ) return luup.variable_get (service, variable,         device) end;
		set = function (x,y) return luup.variable_set (service, variable, y or x, device) end}
end

The reason for the slightly arcane use of two parameters for set and the “[tt]y or x[/tt]” construct is so that set (and get) will also work with the colon notation widely used for objects:

x = a:get()
a:set(42)

In fact, it’s not necessary here because the get/set methods don’t need to access the [tt]self[/tt] parameter since the object’s service, variable, and device parameters are kept as locals in the original closure of the [tt]Variable[/tt] constructor itself.

Don’t know if this helps anyone else, but it works for me and smartens up a lot of code.