【问题标题】:Lua multiple string replacements with string.gsubLua 用 string.gsub 替换多个字符串
【发布时间】: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


【解决方案1】:

整体方法的变体,但最终结果相同。

PATTERN = '^v (%S+) (%S+) (%S+)$'

fo = io.open('object.lua','w')

i = 1
for line in io.lines('file.txt') do
  if line:match(PATTERN) then
    line = line:gsub(PATTERN,'Node'..i..'= {x=%1, y=%2, z=%3}')
    print(line)
    fo:write(line,'\n')
    i = i + 1
  end
end

fo:close()

【讨论】:

  • 非常感谢您为我完成了这项工作!完美运行!
【解决方案2】:

主要问题在于 gsub 调用。您宁愿匹配数字本身 ([^%s]),而不是开头的空格。这样就可以了:

string.gsub(word, "([^%s]) ([^%s]) ([^%s])", "x=%1 y=%2 z=%3", 1)

gmatch 也可以这样简化:

string.gmatch(s, "v [0-9.-]* [0-9.-]* [0-9.-]*")

Live example

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 2016-02-15
    • 1970-01-01
    • 2015-05-18
    • 2011-05-16
    • 2019-04-23
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多