Elmub
Elmub

Reputation: 141

Lua file writing problems

I create a string, print it to see what it looks like, then write it to a file. However the output file is empty and it prints nil. More info in the comments, I'm not really sure what's the cause of the problem here

function main()
    local x = 80
    local y = 25
    local str = ""

    str = str..'map = {\n'

    for i = 1, (y - 1) do
        str = str..'{'

        for i = 1, (x - 1) do
            str = str..'" ",'
        end

        str = str..'" "'
        str = str..'},\n'
    end

    str = str..'{'

    for i = 1, (x - 1) do
        str = str..'" ",'
    end

    str = str..'" "'
    str = str..'}\n'
    str = str..'}'

    --Prints it without problems here
    print(str)

    local file,err = io.open("mapTable.mpt","w")

    if not file then
        return err
    end

    --HERE STR IS NIL???
    print(str)

    file:write(str)
    file:close()
end


local s,err = pcall(main)
if not s then
    print(err)
else
    print("Application ran successfully.")
end
io.read()

Upvotes: 1

Views: 236

Answers (1)

Oliver
Oliver

Reputation: 29483

It's because you aren't raising an error in main, you just return an error string so pcall thinks all is ok and you always end up in the second branch of your if block. Do this instead:

function main()
    ...
    if not file then
        error(err)
    end
    ...
end

local s,err = pcall(main)
if not s then
    print('error caught:', err)
else
    print("Application ran successfully.")
end

Note that err that gets printed will have additional info, it won't be equal to err given to the error function.

Upvotes: 2

Related Questions