LUA: 怎么保存别人的进度?

LUA: how do you save someones progress?

假设您有这样的脚本

print("you've been here for the first time.")
print("you're here for second or more time")

你如何做到一旦一个人运行一次脚本,而不是重复整个脚本,它会立即打印到第二个?

您基本上需要:

  • 程序结束时保存程序状态
  • 恢复程序启动时的状态

有多种存储状态的方法,最简单的方法是创建一个文件并将状态存储在里面。还可以使用 Windows 注册表、数据库、远程服务器等

一个简单的例子:

function FileExists (Filename)
  local File = io.open(Filename, "r")
  if File then
    File:close()
  end
  return File
end

function CreateFile (Filename)
  local File = io.open(Filename, "w")
  if File then
    File:close()
  end
end

ProgramStateFile = "program-state.txt"

if not FileExists(ProgramStateFile) then
  print("you've been here for the first time.")
else
  print("you're here for second or more time")
end

CreateFile(ProgramStateFile)

在这个例子中,状态只是状态文件的存在。显然,您可以通过在文件中写入附加信息来扩展此示例。

function ReadState (Filename)
  local File = io.open(Filename, "r")
  local State
  if File then
    State = File:read("a")
    File:close()
  end
  return State
end

function WriteState (Filename, State)
  local File = io.open(Filename, "w")
  if File then
    File:write(State)
    File:close()
  end
end

ProgramStateFile = "program-state.txt"

if ReadState(ProgramStateFile) ~= "PROGRAM-FINISHED" then
  print("you've been here for the first time.")
else
  print("you're here for second or more time")
end

WriteState(ProgramStateFile, "PROGRAM-FINISHED")

最后,请注意,已经存在许多格式来存储状态:INI 文件、XML、JSON 等。对于Lua,您还可以使用序列化库,以便将 Lua table 直接存储在文件中。我个人会推荐 binser library.