【发布时间】:2021-10-17 13:48:49
【问题描述】:
您好,我正在尝试将存储在 .obj 文件中的顶点转换为可以在 lua 中实际使用的表。
这是 .obj 文件的样子:
# Blender v2.77 (sub 0) OBJ File: ''
# www.blender.org
mtllib pyramid.mtl
o Cube
v 1.000000 0.000000 -1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v -0.000000 2.000000 0.000000
vn 0.0000 -1.0000 0.0000
vn 0.8944 0.4472 0.0000
vn -0.0000 0.4472 0.8944
vn -0.8944 0.4472 -0.0000
vn 0.0000 0.4472 -0.8944
usemtl Material
s off
f 1//1 2//1 3//1 4//1
f 1//2 5//2 2//2
f 2//3 5//3 3//3
f 3//4 5//4 4//4
f 5//5 1//5 4//5
我只需要以 v 开头的 5 行看起来像这样:
Node1= {x=1.000000, y=0.000000, z=-1.000000}
Node2= {x=1.000000, y=0.000000, z=1.000000}
Node3= {x=-1.000000, y=0.000000, z=1.000000}
Node4= {x=-1.000000, y=0.000000, z=-1.000000}
Node5= {x=-0.000000, y=2.000000, z=0.000000}
使用我编写的代码,我管理的输出如下所示:
Node1= {x=1.000000 0.000000 -1.000000}
Node2= {x=1.000000 0.000000 1.000000}
Node3= {x=-1.000000 0.000000 1.000000}
Node4= {x=-1.000000 0.000000 -1.000000}
Node5= {x=-0.000000 2.000000 0.000000}
这就是我的代码在做这项工作:
inputFile = io.open("file.txt", "r")
io.input(inputFile)
string = io.read("*all")
io.close(inputFile)
outputFile = io.open("object.lua", "a")
io.output(otputFile)
i = 1
for word in
string.gmatch(string, " .?%d.%d%d%d%d%d%d .?%d.%d%d%d%d%d%d .?%d.%d%d%d%d%d%d") do
print(word)
-- outputFile:write("Node"..i.. "= {" ..word.. "}\n")
outputFile:write("Node"..i.. "= {" ..string.gsub(word, "(%s)", "x=", 1).. "}\n")
i = i + 1
end
首先它打开 .obj 文件并将所有内容存储在“字符串”中。 比它创建“object.lua”。对于与此模式匹配的每个字符串:
1.000000 0.000000 -1.000000
在字符串中,string.gmatch 会找到它并将其写入输出文件。但首先它必须重新格式化字符串。如您所见,我设法用“x =”替换了第一个空格(%s)。此外,第二个空格需要替换为“, y=”,第三个空格需要替换为“, z=”。 但是我看不到如何使用 string.gsub 来进行多种不同的替换。
这是正确的方法,我只是做错了吗? 还是有其他方法可以完成这项任务?
【问题讨论】:
-
有趣的观察:
string改变了它的含义(因为引入了同名变量),但string.gmatch仍然正确! -
for x, y, z in string:gmatch'\nv%s+(%S+)%s+(%S+)%s+(%S+)''Node'..i..'={x='..x..', y='..y..', z='..z..'}\n'
标签: string serialization lua vertex