A question about classes

I’d like to make a class “Sound” to use it like this:

playingNote = Sound(instr, track, note, vel) – to trigger a note or, if the note already playing, change it

playingNote = nil – to stop note

Is it possible? For now I have

class "Sound"
function Sound:__init( instr, track, note, vel)
	self.instr = instr
	self.track = track
	self.note = note
	self.vel = vel
	client:send(renoise.Osc.Message("/renoise/trigger/note_on", {{ tag = "i", value = instr},{ tag = "i", value = track},{ tag = "i", value = note},{ tag = "i", value = vel}}))
end

function Sound:off()
	client:send(renoise.Osc.Message("/renoise/trigger/note_off", {{ tag = "i", value = self.instr},{ tag = "i", value = self.track},{ tag = "i", value = self.note}}))
end

I didn’t find how to make function in class that executes when you make variable nil. So I had to make function “off”

And to change note, I have to write:

playingNote:off()
playingNote = Sound(instr, track, note, vel)

It works, but I just would like to make it oneliner.

“playingNote = nil” will just nullify the reference to the object (and the whole object will most likely get garbage collected soon enough).

The :off() method is the most obvious way to do what you want to do.

PS. There is also an alternative way if you want to reuse the object instead of creating a new one on each ‘play’. You can then use properties (getter/setter) on something like playingNote.voices - allowing under the hood behaviors, like cutting notes if there are already playing notes. Then you can just do something like “playingNote.voice = 120” at anytime. As always, how all of this would fit is of course slightly depending on the structure of the rest of your code… I can go into details if this sounds interesting.

“playingNote = nil” will just nullify the reference to the object (and the whole object will most likely get garbage collected soon enough).

Yes, and I saw somewhere a function “__gc” (opposite to “__init”) which is triggered when object is set to be garbage collected. But it doesn’t work here.

Or maybe reference can be nullified from “off” function?

reuse the object instead of creating a new one

Can it be done in “init” function or i’ll have to add third one?

I wouldn’t do anything fancy with a gc metamethod (if even available in the Renoise implementation). GC is not reliable in time afaik.

I don’t get what you mean about adding a third one. Anyhow, the init function is only used when creating a new object from a class.