新項目準備使用lua開發,待用資料一般都儲存在csv中,所以參考網上很多資料寫了一個讀取csv檔案的小代碼,由於剛剛接觸lua,所以只是實現了功能,以後再最佳化。
引用xv_ly15與笨木頭的功能配置自己項目需求實現
function split(str, reps) local resultStrsList = {}; string.gsub(str, '[^' .. reps ..']+', function(w) table.insert(resultStrsList, w) end ); return resultStrsList;end--一行一行取用資料local function getRowContent(file) local content; local check = false local count = 0 while true do local t = file:read() if not t then if count == 0 then check = true end break end if not content then content = t else content = content..t end local i = 1 while true do local index = string.find(t, "\"", i) if not index then break end i = index + 1 count = count + 1 end if count % 2 == 0 then check = true break end end if not check then assert(1~=1) end --返回去掉空格的一行資料,還有方法沒看明白,以後再修改 return content and (string.gsub(content, " ", ""))endfunction loadCsvFile(filePath) -- 讀取檔案 local alls = {} local file = io.open(filePath, "r") while true do local line = getRowContent(file) if not line then break end table.insert(alls, line) end --[[ 從第2行開始儲存(第一行是標題,後面的行才是內容) 用二維數組儲存:arr[ID][屬性標題字串] ]] local titles = split(alls[1], ",") local ID = 1 local arrs = {} for i = 2, #alls, 1 do -- 一行中,每一列的內容,第一位為ID local content = split(alls[i], ",") ID = tonumber(content[1]) --儲存ID,以便遍曆取用,原來遍曆可以使用in pairs來執行,所以這個不需要了 --table.insert(arrs, i-1, ID) arrs[ID] = {} -- 以標題作為索引,儲存每一列的內容,取值的時候這樣取:arrs[1].Title for j = 1, #titles, 1 do arrs[ID][titles[j]] = content[j] end end return arrsend