Lua中从文件中读取数字到数组
2016-11-28 2:5:49
收藏:0
阅读:211
评论:2
我有一个文件,它长这样:
一些文字
184 3.7872 184 2.5076
185 3.7891 185 2.5063
186 3.7912 186 2.5042
我想跳过第一行,并将数据写入一个数组中。
我已经有:
local file = io.open("test.txt", "r");
local readFile = {}
for line in file:lines() do
table.insert (readFile, line);
end
--初始化目标数组
local array = {}
for i=2,# readFile,1 do
array[i-1] = {}
for j=1,4,1 do
array[i][j] = 0
end
end
for i=2,# readFile,1 do
--从readFile中拆分行
--将数字写入目标数组
end
当我初始化数组时,似乎有一个我不理解的错误:
lua: script.lua:13: attempt to index a nil value (field '?')
stack traceback:
script.lua:13: in main chunk
[C]: in ?
有人可以帮帮我吗?另外,当我调用readFile[2]时,我得到的是184 3.7872 184 2.5076,我必须将其拆分并写入数组。我该怎么办?
点赞
用户7170955
不需要过度复杂化。
local file = io.open("test.txt", "r");
local array = {}
for line in file:lines() do
local t = {}
for s in line:gmatch("%S+") do
t[#t+1] = tonumber(s)
end
array[#array+1] = t
end
以下是我改动的一点不太好的解释。
local file = io.open("test.txt", "r");
-- local readFile = {} 这也不需要。
local array = {} -- 在此初始化它,更清洁、更简单。
for line in file:lines() do
local t = {} -- 这是我们在数组中的行。
for s in line:gmatch("%S+") do -- 遍历非空白块的字符串。请检查在线 Lua 模式匹配教程。
t[#t+1] = tonumber(s)
end
array[#array+1] = t
--[[ 如果你只想要数字,不关心换行符,只需执行
for s in line:gmatch("%S+") do
array[#array+1] = tonumber(s)
end
这样就可以了。]]
end
-- 删掉底部那部分,我们可以更有效地完成这件事。
一些提示,
- Lua 数组/表不需要初始化,它们是动态的。
- 错误来自于试图索引数组
[i],但你初始化了数组[i-1]。 for i=a, b, c do循环中,只有未指定c的时候才需要指定它不是1。所以for i=1, #lines do同样适用。#不是函数,它是索引(严格来说)。只是与它计数的东西配对看起来更干净而已。使用#lines而不是# lines。
2016-11-28 03:48:10
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

以下方法能够实现目标,但效率很低:
local file = io.open("test.txt", "r"); local readFile = {} for line in file:lines() do table.insert (readFile, line); end --初始化目标数组 local array = {} for i=1,(#readFile)-1,1 do array[i] = {} for j=1,4,1 do array[i][j] = 0 end end function string:split( inSplitPattern, outResults ) if not outResults then outResults = { } end local theStart = 1 local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart ) while theSplitStart do table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) ) theStart = theSplitEnd + 1 theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart ) end table.insert( outResults, string.sub( self, theStart ) ) return outResults end local myTable = readFile[2]:split(" ") for i = 1, #myTable do print( myTable[i] ) -- 这将会得到所需的输出结果 end如果有更高效的方法,我也会很高兴。