1. 程式人生 > >cocos2dx lua解析csv成lua配置檔案,方便程式呼叫

cocos2dx lua解析csv成lua配置檔案,方便程式呼叫

--讀取檔案內容,返回一個字串
function getFile(file_name)
  local f = assert(io.open(file_name, 'r'))  --確保讀取檔案不會錯誤
  local string = f:read("*all") --讀取檔案的所有內容
  f:close()  --這裡記得關閉檔案指標
  return string 
end

function split(str, reps)  --這裡是分割字串的函式
      local resultStrsList = {}
      string.gsub(str, '[^' .. reps ..']+', function(w) table.insert(resultStrsList, w) end )
      return resultStrsList
end

function loadCsvFile(filePath)
      --讀取檔案
      local data = getFile(filePath)
      --按行劃分
      local lineStr = split(data,'\n\r')
      --[[從第三行開始儲存(第一行是標題,第二行是註釋,後面的行才是內容)
      
            用二維陣列儲存:arr[ID][屬性標題字串]
      --]]
      local titles = split(lineStr[1],",")
      --列印第一行的資料
      --print(titles[1]..":"..titles[2])
      for ii=1,#titles,1 do
            print(titles[ii])
      end
      
      local ID = 1
      local arrs = {}
      print(#lineStr)

      local file = io.open("C:/Users/MissionEntry——test.lua", "w")  --這裡會建立一個新的檔案MissionEntry——test.lua
      assert(file)
      file:write("cha = {}\n")
      file:write("cha.MissionEntry = ")
      file:write("{")
      file:write("\n")
      
    


      for i = 3,#lineStr,1 do
            -- 一行中,每一列的內容
            local content = split(lineStr[i],",")
            --以標題作為索引,儲存每一列的內容,取值的時候這樣取:arrs[1].Title
            arrs[ID] = {}
            file:write("             ")
            file:write("[")
            file:write(ID)
            file:write("]={")
            for j=1,#titles,1 do
                  arrs[ID][titles[j]] = content[j]
                  file:write(titles[j])
                  file:write("=")
                  if type(content[j]) == "number" then
                        file:write(content[j])
                  end

                  if type(content[j]) == "string" then
                        
                        if tonumber(content[j]) then  --這裡是判斷數字,如果為真,就寫數字
                              file:write(content[j])
                        else
                              file:write(string.format("%q", content[j])) --如果不是數字,就寫帶有雙引號的字串
                        end
                        
                  end

                  if j ~= #content then  --這裡可以判斷是最後一個就要寫“}”
                        file:write(",")
                  else
                        file:write("}")
                  end
                  
            end
            if i ~= #lineStr then --這裡可以判斷是最後一個就要寫"",也就是空字串
                  file:write(",")
            else
                  file:write("")
            end
            
            file:write("\n")
            file:write("\n")

            ID = ID + 1
      end
      file:write("}")
      file:close()
      return arrs
end


local function main()
      local csvConfig = loadCsvFile("C:/Users/MissionEntry.csv")
end


main()