I moved the callback that updates the mapping to onLoad
Hopefully it will solve the issue.
I have also added a parameter to save the default mapping. It should create a mapping.txt file in your Documents/Steinberg folder. I haven’t tested it thoroughly yet. You can give it a try. Ideally the settings should persists when switching presets.
local mapping = {}
local lastMapping = {}
local initMapping = {}
for i = 0, 127 do
mapping[i] = {i}
lastMapping[i] = i
end
fileLocation = getUserSubPresetPath()
posStart, posEnd = string.find(getUserSubPresetPath(), "Steinberg/")
fileLocation = string.sub(fileLocation, 1, posEnd) .. "mapping.txt"
print(fileLocation)
f, err = io.open(fileLocation, "r")
if f then
data = f:read("*all")
for w in string.gmatch(data, "%d+") do
table.insert(initMapping, tonumber(w))
end
f:close()
end
function saveMapping()
if SaveMapping then
local f, err = io.open(fileLocation, "w")
if f then
f:write(table.concat(lastMapping, " "))
f:close()
end
wait(250)
SaveMapping = false
end
end
defineParameter("SaveMapping", nil, false, saveMapping)
local notes = {[0] = "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
local noteNames = {}
for i = 0, 127 do
local note = notes[i % 12]
local octave = math.floor(i / 12) - 2
noteNames[i] = note .. octave
-- print(note .. octave)
end
local lowestNote = 36
local highestNote = 72
function mappingChanged(i)
local oldNote = lastMapping[i]
local newNote = _G["N"..i]
for j, note in ipairs(mapping[oldNote]) do
if note == i then
table.remove(mapping[oldNote], j)
break
end
end
table.insert(mapping[newNote], i)
lastMapping[i] = newNote
end
for i = lowestNote, highestNote do
defineParameter("N"..i, nil, i, noteNames, function() mappingChanged(i) end)
if initMapping[i] then
_G["N"..i] = initMapping[i]
end
end
function onLoad()
for i = lowestNote, highestNote do
mappingChanged(i)
end
end
function onNote(e)
for i, note in ipairs(mapping[e.note]) do
playNote(note, e.velocity)
end
end