Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Compatibility: Lua-5.1
- function split(str, pat)
- local t = {} -- NOTE: use {n = 0} in Lua-5.0
- local fpat = "(.-)" .. pat
- local last_end = 1
- local s, e, cap = str:find(fpat, 1)
- while s do
- if s ~= 1 or cap ~= "" then
- table.insert(t,cap)
- end
- last_end = e+1
- s, e, cap = str:find(fpat, last_end)
- end
- if last_end <= #str then
- cap = str:sub(last_end)
- table.insert(t, cap)
- end
- return t
- end
- -- transpose function main
- function transposeChordStr(chordSrc, keyShift)
- local chordTable = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }
- local chordKeywordTable = { "C#", "D#", "F#", "G#", "A#", "C", "D", "E", "F", "G", "A", "B" }
- local chordKeyIndexTable = { 1, 3, 6, 8, 10, 0, 2, 4, 5, 7, 9, 11 }
- local chordOut = ""
- local iSrc = 1
- while iSrc <= #chordSrc do
- -- replace chord if possible
- local chordReplaced = false
- for iToken, chordToken in pairs(chordKeywordTable) do
- local iStart, iEnd = string.find(chordSrc, chordToken, iSrc, true)
- if iStart == iSrc then
- local newChord = chordTable[(chordKeyIndexTable[iToken] + keyShift) % 12 + 1]
- chordOut = chordOut .. newChord
- iSrc = iSrc + #chordToken
- chordReplaced = true
- break
- end
- end
- --
- if not chordReplaced then
- chordOut = chordOut .. chordSrc:sub(iSrc, iSrc)
- iSrc = iSrc + 1
- end
- end
- return chordOut
- end
- -- parse command line options
- local chordFilePath = "chords.txt"
- local keyShift = 0
- if #arg == 1 then
- keyShift = tonumber(arg[1])
- elseif #arg == 2 then
- chordFilePath = arg[1]
- keyShift = tonumber(arg[2])
- else
- error("Unsupported option.")
- return
- end
- -- open chords.txt
- local chordFile = io.open(chordFilePath, "r")
- if chordFile == nil then
- stderr.write("Unable to open: " .. chordFilePath)
- end
- -- process for each lines
- for line in chordFile:lines() do
- -- split codes into an array
- local chordsIn = split(line, " ")
- for i, chordSrc in pairs(chordsIn) do
- local chord
- if i == 1 then
- chord = chordSrc
- else
- chord = transposeChordStr(chordSrc, keyShift)
- io.write(" ")
- end
- io.write(chord)
- end
- io.write("\n")
- end
- chordFile:close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement