如何从文件中读取特定数字

时间:2015-12-02 14:16:26

标签: variables lua

我想写一个Lua脚本,它会将我的vars保存并加载到我的程序中。我在互联网上搜索了一些代码示例,现在我有了这个:

--SetUp vars
accept = 1
strenght = 5
hp = 2

--create file
local f = assert(io.open("quicksave", "w"))
f:write(accept, "\n")
f:write(strenght, "\n")
f:write(hp, "\n")
f:close()

--Set vars to 0(simulate restart of program)
accept = 0
strenght = 0
hp = 0
print("accept: "..accept.."   Strenght: "..strenght.."   HP: "..hp)

--load in the saved vars
local f = assert(io.open("quicksave", "r"))
accept = f:read("*line")
strenght = f:read("*line")
hp = f:read("*line")
f:close()
print("accept: "..accept.."   Strenght: "..strenght.."   HP: "..hp)

这对我来说很好,但是如何只读取文件中的特定值?例如:如果我只想读出文件的第二行(强度的var),我该怎么办?

1 个答案:

答案 0 :(得分:1)

您只需阅读并放弃第一行:

--load in the second saved var
local f = assert(io.open("quicksave", "r"))
f:read("*line")
strenght = f:read("*line")

尽管如此,我建议您将数据保存为可以加载dofile的Lua脚本。类似的东西:

return {
  accept = 1,
  strenght = 5,
  hp = 2
}

然后你可以将它加载到局部变量中并读取你需要的字段:

local state = dofile("state.lua")
strenght = state.strenght