【问题标题】:Creating new folders and files with Lua使用 Lua 创建新文件夹和文件
【发布时间】:2013-04-16 05:36:06
【问题描述】:

我正在编写一个供个人使用的 Lua 5.1 脚本,旨在通过 Lua 解释器作为独立程序运行。我需要包含一个函数,该函数将创建一个新的子文件夹(其中“mainfolder”包含脚本和一个名为“season”的文件夹,新文件夹被创建为“season”的子文件夹),然后编写返回的文本字符串新文件夹中的新文本文件的另一个功能。这是在 Windows 8 上。由于我通常不擅长解释事情,这里有一些伪代码来说明:

function makeFiles()
    createfolder( ".\season\week1" )
    newFile = createFile( ".\season\week1\game.txt" )
    newFile:write( funcThatReturnsAString() )
    newFile:close()
end

我知道如何打开和写入与脚本相同的文件夹中的现有文件,但我不知道如何 1) 创建子文件夹,以及 2) 创建一个新文件。我该怎么做?

【问题讨论】:

    标签: file file-io lua directory execute


    【解决方案1】:

    要创建文件夹,您可以使用os.execute() 调用。对于文件写入,一个简单的io.open() 就可以完成这项工作:

    function makeFiles()
        os.execute( "mkdir season\\week1" )
        newFile = io.open( "season\\week1\\game.txt", "w+" )
        newFile:write( funcThatReturnsAString() )
        newFile:close()
    end
    

    编辑

    在 Windows 中,您需要对路径使用双反斜杠 (\\)。

    【讨论】:

    • 好的,这比我想象的要简单。我认为如果文件不存在,io.open() 会返回错误。谢谢。
    【解决方案2】:

    os.execute 有效,但应尽可能避免使用,因为它不可移植。 LuaFileSystem 库就是为此目的而存在的。

    【讨论】:

    • 知道了。 os.execute 可能适合这项任务,因为相关程序只能在我的计算机上运行,​​但我会在以后的项目中牢记可移植性问题。
    【解决方案3】:
    function myCommandFunction(playerid, text)
        if(string.sub(text, 1, 5) == "/save") then
            local aName = getPlayerName(playerid)
            os.execute( "mkdir filterscripts\\account" )
            file = io.open(string.format("filterscripts\\account\\%s.txt", aName), "w")
            file:write(string.format("Name: %s", aName))
            file:close()
        end
    end
    registerEvent("myCommandFunction", "onPlayerCommand")
    

    Basic: Create accound for game (example)

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      相关资源
      最近更新 更多