使用lua讀取csv文件

新項目準備使用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, " ", ""))
end

function 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 arrs
end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章