I want to read an OBJ file in Lua. I am new to the file writing/reading system in Lua and wouldn't know how I would do that. What I want to do: I want to read each line and see if the line starts with a "v" if it does I take the numbers after that and store them in a Vector3. Then I wanna find the lines with "f", and I wanna take the numbers that "f" gives and store that Vector3 in a Polygon object. Example:
v 4.0 7.0 5.0
v 1.0 5.0 1.0
v 5.0 4.0 2.0
v 6.0 1.0 7.0
f 1 4
f 3 2
So Vector 1 would be (4,7,5). 2 (1,5,1). 3 (5,4,2). 4 (6,1,7)
Mesh number one would be made up of Vector 1 and 4
Mesh number two would be made up of Vector 3 and 2
This was meant as a short example.
As some might know the f actually look something like this:
f 1/1/1 2/4/1 4/9/1 3/7/1
So if there is a way to separate them by the / too, that would be great.
I want to be able to read and store the data of an OBJ file in lua.
You can store it in obj
obj = io.open('path/to/file'):read('*a')
After that you can work with it.
Following is only an example how powerfull gsub()
could be...
> obj:gsub('(%l) (%d+%.%d+) (%d+%.%d+) (%d+%.%d+)', function(a, b, c, d) return(('<%s> [%.1f] [%.1f] [%.1f]'):format(a, b, c, d)) end)
<v> [4.0] [7.0] [5.0]
<v> [1.0] [5.0] [1.0]
<v> [5.0] [4.0] [2.0]
<v> [6.0] [1.0] [7.0]
f 1 4
f 3 2 4
> obj:gsub('(%l) (%d+) (%d+)', function(a, b, c) return(('<%s> [%s] [%s]'):format(a, b, c)) end)
v 4.0 7.0 5.0
v 1.0 5.0 1.0
v 5.0 4.0 2.0
v 6.0 1.0 7.0
<f> [1] [4]
<f> [3] [2] 2
...done in Lua Standalone.
In the Function of gsub()
you can do something with the Match on Pattern.