Most efficient way to parse a file in Lua

2019-09-13 15:48发布

问题:

I'm trying to figure out what is the most efficient way to parse data from a file using Lua. For example lets say I have a file (example.txt) with something like this in it:

0, Data
74, Instance
4294967295, User
255, Time

If I only want the numbers before the "," I could think of a few ways to get the information. I'd start out by getting the data with f = io.open(example.txt) and then use a for loop to parse each line of f. This leads to the heart of my question. What is the most efficient way to do this?

In the for loop I could use any of these methods to get the # before the comma:

line.find(regex)
line:gmatch(regex)
line:match(regex)

or Lua's split function

Has anyone run test for speed for these/other methods which they could point out as the fast way to parse? Bonus points if you can speak to speeds for parsing small vs. large files.

回答1:

You probably want to use line:match("%d+").

line:find would work as well but returns more than you want.

line:gmatch is not what you need because it is meant to match several items in a string, not just one, and is meant to be used in a loop.

As for speed, you'll have to make your own measurements. Start with the simple code below:

for line in io.lines("example.txt") do
  local x=line:match("%d+")
  if x~=nil then print(x) end
end