Lua - 将表转换为逗号分隔列表
我需要将表转换为逗号分隔的列表,以便将其保存到文本文件中。 Lua 中有内置方法可以做到这一点吗?
I need to convert a table into a comma separated list in order to save it to a text file. Is there a built in method for doing this in Lua?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的表是数组,则可以使用
table.concat
打印 CSV:输出
10,20,30
。If your table is an array, you can use
table.concat
to print CSVs:outputs
10,20,30
.没有内置函数,但网上有示例。
这实际上是一个不错的。
There isn't a built in function, but there are examples onthe web.
This is a decent one actually.
不,没有为此的“内置”功能。但自己做并不难。我保留了一个脚本,用于将 Lua 表作为 Lua 脚本直接递归写入文件,然后可以像 Lua 脚本一样加载和执行。
No, there is not a "built in" function for this. But it's not hard to do it yourself. I keep a script around for recursively writing Lua tables directly to files as Lua scripts, which can then be loaded and executed like Lua scripts.
没有内置的方式,但如果您想自己构建,有很多相对容易的选项。以下是一些链接,可以帮助您弄清楚如何将它们组合在一起:
http://www .lua.org/pil/12.1.html
http://lua-users.org/wiki/TableSerialization
There is not a built in way, but there are a number of options that are relatively easy if you want to build it yourself. Here are some links that can help you figure out how you want to put it together:
http://www.lua.org/pil/12.1.html
http://lua-users.org/wiki/TableSerialization
是的,有一个内置方法,并且它已经存在很长时间了。
您可以使用此函数将表格转换为字符串,只需选择“,”作为分隔符即可。
您还可以添加一个在串联期间运行的函数,并检测您编写了多少个属性,然后添加一个新行 - 如果需要,您可以制作一个非常复杂的转换器。
我的建议是打破逗号分隔表的每一“行”,并用“,”连接每个“行”,然后将其写出来。这样您就可以确保可以处理大量行,并且每行的格式都正确。
注意事项:
连接参考:
http://www.lua.org/manual/5.1/ Manual.html#pdf-table.concat
Yes, there is a builtin method, and its been around for a very long time.
You can convert a table to a string using this function, and simply choose a "," for a separator.
You can also add a function that runs during concatenation and detects how many properties you have written, then add a new line - you can make a very complex converter if you need.
My recommendation is to break each "line" of comma separated tables and concat each one with "," then write it out. This way you can be sure that you can handle large numbers of lines, and that each line is correctly formatted.
Caveats:
Reference for concat:
http://www.lua.org/manual/5.1/manual.html#pdf-table.concat