lua-users home
lua-l archive

Re: Reading Particular contents from file

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 01/25/2012 09:21 AM, Sandeep Ghai wrote:
Hello everyone,
I am doing file handling using Lua programming. But I need some help
where I got stuck.
I want to read particular line from the file.
consider the following file:-
...
I want to read 'x',and 'y' values whenever I pass argument to read
'nodes' and similarly for other contents(like constraint,forces etc) too.
After then I want to pass all these things directly into database,to
gather all the similar things from number of files.
Please help me in syntax. I am a beginner in Lua Programming.
Thank you in advance.
While the more professional thing to do would be to use LPEG, this is a fast and only slightly error-prone way to get it done with string.match and tail-calls as a state machine. Call parse_data_description with a file handle and it will produce a table. Then move it into the database with whatever backend you're using. I guessed at what fields may be optional, so you'll want to tweak the 'material or "beam"' like expressions.
local headings
local function parse_problem_description(T, F)
 local line = F:read()
 if not line then
 return T
 end
 if headings[line] then
 return headings[line](T, F)
 end
 local title = string.match(line, '^title="([^"]*)"')
 if title then
 T.title = title
 end
 return parse_problem_description(T, F)
end
local function parse_nodes(T, F)
 local line = F:read()
 if not line then
 return T
 end
 if headings[line] then
 return headings[line](T, F)
 end
 local i,x,y = string.match(line, '^(%d+) +x=(%d+) +y=(%d+)')
 if i then
 i,x,y = tonumber(i),tonumber(x),tonumber(y)
 local constraint = string.match(line, 'constraint=(%a+)')
 local force = string.match(line, 'force=(%a+)')
 T.nodes[i] = {
 x = x,
 y = y,
 constraint = constraint or 'free',
 force = force
 }
 end
 return parse_nodes(T, F)
end
local function parse_beam_elements(T, F)
 local line = F:read()
 if not line then
 return T
 end
 if headings[line] then
 return headings[line](T, F)
 end
 local i,n1,n2 = string.match(line, '^(%d+) +nodes=%[(%d+),(%d+)%]')
 if i then
 i,n1,n2 = tonumber(i),tonumber(n1),tonumber(n2)
 local material = string.match(line, 'material=(%a+)')
 T.elements[i] = {
 nodes = {n1,n2},
 material = material or 'beam'
 }
 end
 return parse_beam_elements(T, F)
end
headings = {
 ['problem description'] = parse_problem_description;
 ['nodes'] = parse_nodes;
 ['beam elements'] = parse_beam_elements;
}
function parse_data_description(F)
 local T = { title="", nodes = {}, elements = {} }
 return parse_problem_description(T, F)
end
--
- tom
telliamed@whoopdedo.org

AltStyle によって変換されたページ (->オリジナル) /