-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv2lua.lua
More file actions
97 lines (93 loc) · 3.18 KB
/
Copy pathcsv2lua.lua
File metadata and controls
97 lines (93 loc) · 3.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
local csv2lua = {}
function csv2lua.parse(filePath, separator, headers)
--If headers is not specified, set to false
if headers == nil then headers = false end
--Open file
local file = io.open(filePath, "r")
local outputTable = {}
--Check that file exists
if file ~= nil then
--Read first line
local fileLine = file:read()
local indexRow = 1
local headersTable = {}
local firstLine = true
--If line is read, aka not EOF
while fileLine ~= nil do
outputTable[indexRow] = {}
local indexCol = 1
local charStart = 1
local charEnd = 1
--Check for EOL
while fileLine:len() > charStart do
--Read until separator or EOL
while fileLine:sub(charEnd, charEnd) ~= separator and charEnd ~= fileLine:len() do
charEnd = charEnd + 1
end
--Ignore separator
charEnd = charEnd - 1
--Save headers, if applicable
if firstLine and headers then
headersTable[indexCol] = fileLine:sub(charStart, charEnd)
else
--Index with headers if aavailible
if headers then
if charStart > charEnd then
outputTable[indexRow][headersTable[indexCol]] = nil
else
outputTable[indexRow][headersTable[indexCol]] = fileLine:sub(charStart, charEnd)
end
--Index with numbers if headers are not availible
else
if charStart > charEnd then
outputTable[indexRow][indexCol] = nil
else
outputTable[indexRow][indexCol] = fileLine:sub(charStart, charEnd)
end
end
end
indexCol = indexCol + 1
charStart = charEnd + 2
charEnd = charEnd + 2
end
--Read next line
fileLine = file:read()
if firstLine then
firstLine = false
else
indexRow = indexRow + 1
end
end
end
--Close file, return result
io.close(file)
return outputTable
end
function csv2lua.toCsv(tb, separator, headers)
if csv2lua.verifyTable(tb) then
for i, v in pairs(tb) do
tb[i] = table.concat(v, ";")
end
tb = table.concat(tb, "\n")
return tb
else
print("Table verification failed")
end
end
--Function to check that the provided table can be converted to CSV
function csv2lua.verifyTable(table)
for i, v in pairs(table) do
if type(v) ~= "table" then
print("Only two-dimentional tables can be converted to CSV")
return false
end
for i, s in pairs(v) do
if type(s) == "table" then
print("Only two-dimentional tables can be converted to CSV")
return false
end
end
end
return true
end
return csv2lua