Lua 5.2:更新系统(需要帮助)

时间:2014-10-27 11:56:42

标签: io lua

我需要Lua中FileEditing的帮助,因为我只是想把它给我们...

那是我的代码:

local clientFile, serverFile = io.open("client.txt", "r"), io.open("server.txt", "r")

local clientVer, serverVer = tostring(clientFile:read()), tostring(serverFile:read())

io.write("\nCurrent Version: "..clientVer.."\nLast Version: "..serverVer.."\n\n")

if clientVer == serverVer then
    io.write("No Updates for now.\n\n")
elseif clientVer ~= serverVer then
    io.write("Updating...\n\n")
    os.remove("client.txt")
    local clientFileW = io.open("client.txt", "w+")
    clientFileW:write(serverVer)
    local clientFileR = io.open("client.txt", "r")
    io.write("Client Updated!\n\n")
    io.write("Current Version: "..tostring(clientFileR:read()).."\nLast Version: "..serverVer.."\n\n")
end

当我在Client-Server中拥有相同版本时,这是我的输出:

Current Version: v2
Last Version: v2

No Updates for now.

当我有敌人时我的输出示例客户端:v1和服务器:v8

Current Version: v1
Last Version: v8

Updating...

Client Updated!

Current Version: nil
Last Version: v8

我为什么没有这个?

1 个答案:

答案 0 :(得分:2)

这里的问题是输出被缓冲(即没有立即写入文件)。此缓冲由C library functions which Lua uses for IO完成。以下是代码中发生的事情:

    -- ...
    -- new, empty file is created
    local clientFileW = io.open("client.txt", "w+")
    -- server version is stored in an internal buffer, waiting to be written to
    -- the file
    clientFileW:write(serverVer)
    local clientFileR = io.open("client.txt", "r")
    -- the empty client.txt is opened
    io.write("Client Updated!\n\n")
    -- since the client.txt file is empty, nil is returned by clientFileR:read()
    io.write("Current Version: "..tostring(clientFileR:read())
             .."\nLast Version: "..serverVer.."\n\n")
end
-- end of program execution, flush buffers (e.g. write the new version),
-- close files, etc.

要解决您的程序,您可以在编写新客户端版本后添加对:flush()的调用。这将强制在该点将内部缓冲区写入文件:

-- ...
local clientFileW = io.open("client.txt", "w+")
clientFileW:write(serverVer)
clientFileW:flush()
local clientFileR = io.open("client.txt", "r")
-- ...