PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How to read CSV files in lua

 August 28, 2022     csv, lua     No comments   

Issue

I am trying to read a .csv file that has length and quantity columns. I am able to read the first column ( 12.5, 10, 8....) but the quantity field is always empty. I am obviously new to lua and was wondering if anyone had an idea as to why by quantity is always empty.

function ReadFileNameWindows(PassedInWindowsPath)
local fileList = {}
for line in io.lines(PassedInWindowsPath) do
local length,quantity = line:match("%s*(.-),%s*(.-)")
    print(length)
    print(quantity)
    fileList[#fileList + 1] = { length = length, quantity = quantity } 
    end

Solution

Your pattern is wrong. line:match("%s*(.-),%s*(.-)") will first consume some spacing, then match some characters until the first ,, then again match some spacing, then match nothing (the empty string). That's because .- is a lazy match: It matches as little as possible (can be zero characters) for the pattern to match. As nothing comes after (.-), it will always match the empty string.

To fix this, simply use the greedy quantifier * (zero or more occurrences). line:match("%s*(.-),%s*(.*)"). This will match anything after the spacing after the first comma to the end of the string.

Furthermore, if you want to trim trailing spacing, use line:match("%s*(.-),%s*(.-)%s*$"). Note that I've changed .* back to .- since now there is %s*$ after it which must match: $ anchors the pattern at the end of the line, meaning .- can't stop matching early; %s* consumes all trailing spacing before the end of the line.

Reading CSV is easy enough that you probably won't need a library for it.



Answered By - LMD
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing