gpt4 book ai didi

lua - 在Lua中将x y z的列文件读入表中

转载 作者:行者123 更新时间:2023-12-04 14:05:11 24 4
gpt4 key购买 nike

一直试图通过Lua找到我的方法,所以我有一个包含N行数字的文件,每行3个,它实际上是x,y,z坐标。我可以将其设为 CSV 文件并使用一些 Lua CSV 解析器,但我想无论如何,如果我学会如何执行此操作会更好。

那么处理这个问题的最佳方法是什么?到目前为止,我可以通过下面的代码片段将每一行读入表行,但是1)我不知道这是一个字符串表还是数字表,2)如果我打印tbllinesx [1],它会打印整个表三个数字的行。我希望能够让 tbllines[1][1]、tbllines[1][2] 和 tbllines[1][3] 对应于我的文件第一行的前 3 个数字。

local file = io.open("locations.txt")
local tbllinesx = {}
local i = 0
if file then
for line in file:lines() do
i = i + 1
tbllinesx[i] = line
end
file:close()
else
error('file not found')
end

最佳答案

来自 Lua 编程 https://www.lua.org/pil/21.1.html

You can call read with multiple options; for each argument, the function will return the respective result. Suppose you have a file with three numbers per line:

6.0 -3.23 15e12

4.3 234 1000001

... Now you want to print the maximum of each line. You can read all three numbers in a single call to read:

while true do
local n1, n2, n3 = io.read("*number", "*number", "*number")
if not n1 then break end
print(math.max(n1, n2, n3))
end

In any case, you should always consider the alternative of reading the whole file with option "*all" from io.read and then using gfind to break it up:

local pat = "(%S+)%s+(%S+)%s+(%S+)%s+"
for n1, n2, n3 in string.gfind(io.read("*all"), pat) do
print(math.max(n1, n2, n3))
end

我相信您可以弄清楚如何修改它以将数字放入您自己的表字段中。

如果您使用三个捕获,则只需使用 table.pack 创建包含三个条目的行表。

关于lua - 在Lua中将x y z的列文件读入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47332152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com