Convert a CSV file to a table with specific keys in Lua

I am learning Lua to create scripts for a flight simulator.

I have a CSV file that looks like this:

Poti city, Poti,red,-295731.42857144,617222.85714285  
Lanchhuti city, Poti,red,-299217.14285715,647851.42857142  
Ozurgeti city, Poti,red,-317217.14285715,648422.85714285  
Samtredia city, Poti,red,-287502.85714287,672022.85714285  
Abasha city, Poti,red,-284245.71428573,661108.57142857

Each row contains 5 fields ( city, region, coalition, coordinate-xand coordinate-yin simulators coordinate system).

I need to read this file as a lua table, which should look like this:

citylist = {
           [1]
           {
              ["city"] = "Poti city",
              ["region"] = "Poti",
              ["coalition"] = "red",
              ["coordinate-x"] = -295731.42857144,
              ["coordinate-y"] = 617222.85714285,
           },
           [2]
           { ....... etcetc

}

I also need to do this for some different csv files, and I tried to look at some of the CSV functions from luawiki, but I honestly don't understand much. Can you write some sample code that should work for parsing a CSV file?

PS: a symbol is never present in csv files ' " '.

EDIT + ADD

ok 1, , , , , , . , .

:

123,Poty city,Poti,red,-295731.42857144,617222.85714285
124,Lanchhuti city,Poti,red,-299217.14285715,647851.42857142
125,Ozurgeti city,Poti,red,-317217.14285715,648422.85714285
126,Samtredia city,Poti,red,-287502.85714287,672022.85714285

:

do  
    local OLo = io.open(lfs.writedir() .. "Logs/" .. "Objectivelist.txt", "r")
    local Objectivelist = {}
    for line in io.lines(OLo) do
        local objID, objName, objRegion, objCoalition, objCoordx, objCoordy = line:match("%s*(.-),%s*(.-),%s*(.-),%s*(.-),%s*(.-),%s*(.-)")
        Objectivelist[#Objectivelist + 1] = { ["objID"] = objID, ["objName"] = objName, ["objRegion"] = objRegion, ["objCoalition"] = objCoalition, ["objCoordx"] = objCoordx, ["objCoordy"] = objCoordy }
    end
end

differe :

do
    local fName = "DGWS-DEBUG-objectivelist.doc"
    local f = io.open(lfs.writedir() .. "Logs/" .. fName, "w")
    local debugOBJ = ""

    for ind, objData in pairs(Objectivelist) do
        debugOBJ = debugOBJ.. objData.objID .. "," .. objData.objName .. "," .. objData.objRegion .. "," .. objData.objCoalition .. "," .. objData.objCoordx .. "," .. objData.objCoordy .. "\n"
    end

    f:write(debugOBJ)

end 

, " ind, objData (Objectivelist) " ", , .

, :(, ?

:)

PS: , , :)

+4
2

CSV . , , .

local citylist = {}
for line in io.lines("citys.csv") do
    local city, region, coalition, coordinate_x, coordinate_y = line:match("%s*(.-),%s*(.-),%s*(.-),%s*(.-),%s*(.-)")
    citylist[#citylist + 1] = { city = city, region = region, coalition = coalition, coordinate_x = coordinate_x, coordinate_y = coordinate_y }
end

. , , .

+5

, Shan Carter Mr. Data Converter. Lua.

http://thdoan.imtqy.com/mr-data-converter/

CSV Lua: ( ).

0

All Articles