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

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

原文链接 https://stackoverflow.com/questions/16029504

点赞
stackoverflow用户1190388
stackoverflow用户1190388

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

2013-04-16 05:56:28
stackoverflow用户204011
stackoverflow用户204011

os.execute 可以使用,但应该尽可能避免,因为它不可移植。LuaFileSystem 库存在的目的就是为了解决这个问题。

2013-04-16 08:45:41
stackoverflow用户13844645
stackoverflow用户13844645
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")

基础: 为游戏创建账号(示例)

2020-07-04 10:47:10