Programming Fundamentals/Files/Lua

From Wikiversity
Jump to navigation Jump to search

files.lua[edit]

-- This program creates a file, adds data to the file, displays the file,
-- appends more data to the file, displays the file, and then deletes the file.
-- It will not run if the file already exists.
--
-- References:
--     https://www.mathsisfun.com/temperature-conversion.html
--     https://www.lua.org/manual/5.1/manual.html

function create_file(filename)
    local file 
    
    file = io.open(filename, "w")
    file:write("C\tF\n")
    for c = 0, 50, 1 do
        f = c * 9 / 5 + 32
        file:write(c .. "\t" .. f .. "\n")
    end
    file:close()
end

function read_file(filename)
    local file 
    local line
    
    file = io.open(filename, "r")
    while true do
        line = file:read()
        if line == nil then 
            break 
        end
        io.write(line, "\n")
    end
    file:close()
    io.write("\n")
end

function append_file(filename)
    local file = io.open(filename, "a")
    for c = 51, 100, 1 do
        f = c * 9 / 5 + 32
        file:write(c .. "\t" .. f .. "\n")
    end
    file:close()
end

function delete_file(filename)
    os.remove(filename)
end

function file_exists(filename)
    local file
    
    file = io.open(filename, "r")
    if file ~= nil then 
        file:close()
        return true
    else
        return false
    end
end

function main()
    local filename = "~file.txt"

    if file_exists(filename) then
        io.write("File already exists.")
    else
        create_file(filename)
        read_file(filename)
        append_file(filename)
        read_file(filename)
        delete_file(filename)
    end
end
    
main()

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own Lua compiler / interpreter / IDE.

See Also[edit]