Skip to content

Instantly share code, notes, and snippets.

@CapsAdmin
Created September 27, 2018 11:58
Show Gist options
  • Save CapsAdmin/aea25c319c2b6e42360057c5c527ba34 to your computer and use it in GitHub Desktop.
Save CapsAdmin/aea25c319c2b6e42360057c5c527ba34 to your computer and use it in GitHub Desktop.
csv to table
local function split(self, separator, plain_search)
if plain_search == nil then
plain_search = true
end
local tbl = {}
local current_pos = 1
for i = 1, #self do
local start_pos, end_pos = self:find(separator, current_pos, plain_search)
if not start_pos then break end
tbl[i] = self:sub(current_pos, start_pos - 1)
current_pos = end_pos + 1
end
if current_pos > 1 then
tbl[#tbl + 1] = self:sub(current_pos)
else
tbl[1] = self
end
return tbl
end
function csv2tbl(content)
local rows = {}
local keys
for i, line in ipairs(split(content, "\n")) do
local values = split(line, ";")
if i == 1 then
keys = values
else
local row = {}
for i, value in ipairs(values) do
row[keys[i]] = value
end
rows[i - 1] = row
end
end
return rows
end
local tbl = csv2tbl(io.open("/home/caps/johan/Users/johan/smakeappen/MockData/produkter.csv"):read("*all"))
for i, row in ipairs(tbl) do
io.write(i, ":\n")
for key, val in pairs(row) do
io.write("\t", key, " = ", val, "\n")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment