Most efficient way to parse a file in Lua

纵然是瞬间 提交于 2020-01-17 04:31:05

问题


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


来源:https://stackoverflow.com/questions/25026530/most-efficient-way-to-parse-a-file-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!