使用Lua创建新文件夹和文件

时间:2013-04-16 05:36:07

标签: file file-io lua directory execute

我正在编写一个供个人使用的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)创建一个新文件。我该怎么做?

3 个答案:

答案 0 :(得分:3)

要创建文件夹,您可以使用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中,您需要为路径使用双反斜杠(\\)。

答案 1 :(得分:3)

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

答案 2 :(得分:0)

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)

相关问题