【问题标题】:file.write not working from a different .luafile.write 不能从不同的 .lua 工作
【发布时间】:2014-08-05 05:35:52
【问题描述】:

我编写了一个 lua 函数,以特定方式将输入的文本添加到 users.txt,单独执行时效果很好,但是当我在 main.lua 中需要它时它可以工作 - 但从不写入 users.txt。 这是我的两个文件的代码:

adminprograms.lua:

function adduser()
    print("Username")
    local username = io.read()
    print("Password")
    local password = io.read()
    print("State")
    local state = io.read()
    state = state.upper(state)
    print(state.."-"..username.."-"..password)
    --------------the code that dosent work
    local users = io.open("users.txt", "a" )
    users.write(users , state.."-"..username.."-"..password.."\n")
end

main.lua:

require "adminprograms"
loginstate = "admin"
repeat
local command = io.read()
if loginstate == "admin" and command == "newuser" then
    adduser()
end
until false

这是为什么?它们都与 users.txt 位于同一个文件夹中。如果这很重要,我正在运行 Windows 64 位。不会抛出任何错误。

【问题讨论】:

  • 所以当您使用main.lua 时,您会看到打印消息,但退出后的文件没有任何附加内容?
  • 我不知道,这就是我问的原因:)

标签: function io lua require


【解决方案1】:

我看不出有什么问题,但是

  • 这不能是您运行的代码,因为最后一行会导致错误。虽然与错误无关,但它表明可能还有其他您未放置的代码可能是错误的来源。
  • 写入操作是缓冲的(仅当写入缓冲区已满时它们才会写入磁盘)所以可以肯定的是,您应该 close() 文件对象或至少 flush() 它:

    ... Call users:write() as (many times as) required, then when done:
    users:close()
    

    或者

    ... 
    users:write() -- if you're going to check the file contents in an editor:
    users:flush()
    

风格(与问题无关):使用冒号符号,这样您就不必重复对象:users:write() 而不是 users.write(users)

【讨论】:

  • 哎呀,删掉了重复。我一定会补充的。但是,我认为这不是导致问题的原因。
  • 还有,冒号?那究竟是什么?我用谷歌搜索了它,但这样的东西很难用谷歌搜索。
  • x:f(y)x.f(x, y) 相同——它是面向对象风格编程的便捷语法。
【解决方案2】:

如果您在最后调用users:close()adduser 应该可以正常工作。

参考手册说“请注意,当文件的句柄被垃圾收集时,文件会自动关闭,但这需要不可预知的时间才能发生。”在立即发生的独立情况下,在程序终止时。 (更准确地说,文件句柄被标记为终结,终结器是关闭文件,终结在 Lua 状态结束时执行。)但是由于 main.lua 不会立即终止,垃圾收集/终结被推迟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2011-09-01
    • 2014-12-21
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多