LUA array fun

I don’t know how useful this might be to the general population, but I had a need and so here’s a LUA discovery that might help folks.

Goal - I want to change the name/destination/value of a set of controls (tracks 1-8). Sometimes I want the control to change volume, or pan position or other stuff. Ideally, I want to be able to save the last set value so when I come back to a control that’s been edited, the display reflects the current value.

To start, I set up some arrays with default values:

ccMap = {38, 39, 40, 41}
trkCCName = {"Volume", "Feedback", "Pan", "Speed"}
trkVol = {127, 127, 127, 127, 127, 127, 127, 127}
trkFbk = {127, 127, 127, 127, 127, 127, 127, 127}
trkPan = {64, 64, 64, 64, 64, 64, 64, 64}
trkSpd = {127, 127, 127, 127, 127, 127, 127, 127}

Then I set up an array to access these things (has to be defined after the initial arrays):

tblIdx = 1
trkTbl = {trkVol, trkFbk, trkPan, trkSpd}

I defined a virtual fader to select what function will be used. The fader has a min=1, max=4, and a list array of strings and values. Each track control will send out a MIDI Note and a MIDI CC, so there’s some processing to get the CC associated with the function here. Currently, the 8 track controls have IDs 31-38 (working on removing some hardcoding - functionality first though):

function setTrkCC(ValueObject, Value)
   local message = ValueObject:getMessage()
   tblIdx = message:getValue ()
   local valueTbl = trkTbl[tblIdx]

   ccFn = ccMap[tblIdx]
   for i=1,8 do
      local ctl = controls.get(30 + i)
      ctl:setName(string.format("%s %d", trkCCName[tblIdx], i))
      parameterMap.set(1, PT_VIRTUAL, 30+i, valueTbl[i])

Next, each of the 8 track faders call this LUA function to actually send out the values:

function trkCCFunc(ValueObject, Value)
   local control = ValueObject:getControl()
   local ctrlId = control:getId()
   local trkNum = ctrlId - 30

   local valueTbl = trkTbl[tblIdx]

   valueTbl[trkNum] = Value

   midi.sendNoteOn(PORT_1, 1, trkNum, 127)
   midi.sendControlChange(PORT_1, 1, ccFn, Value)

The main thing I wanted to avoid was a bunch of “if then else” constructs to handle which table and value to use. By creating an array of array names, LUA lets you index into that, grab a name and then use that to get/set values. To extend it and add more functions per track is simply a matter of extending the array