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



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

function makeFiles()
    createfolder( ".seasonweek1" )
    newFile = createFile( ".seasonweek1game.txt" )
    newFile:write( funcThatReturnsAString() )
    newFile:close()
end

我知道如何打开并写入与脚本相同文件夹中的现有文件,但我无法弄清楚的是如何1)创建子文件夹,以及2)创建新文件。我该怎么做呢?

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

os.execute工作,但应尽量避免,因为它是不可移植的。LuaFileSystem库就是为了这个目的而存在的。

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")

基本:为游戏创建帐户(示例)

最新更新