2014-09-04 130 views
1

我創建一個字符串,打印它看看它的樣子,然後將它寫入文件。然而,輸出文件是空的,它打印零。在評論中更多信息,我真的不知道有什麼問題的原因在這裏Lua文件寫入問題

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() 
+2

'如果不是f然後'?你從不聲明變量'f'。 – hjpotter92 2014-09-04 07:19:26

+0

更改爲文件,而不是f,但顯然不能解決任何問題:/ – Elmub 2014-09-04 07:23:17

+0

我試過你的代碼,它適用於我... – Maze 2014-09-04 09:03:06

回答

2

那是因爲你沒有養主的錯誤,你就這麼PCALL認爲一切正常返回錯誤的字符串並且你總是在你的if塊的第二個分支中結束。做到這一點,而不是:

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 

注意err是被印刷將有進一步的信息,這將不等於給予error功能err