我创建一个字符串,打印它以查看它的外观,然后将其写入文件。但是输出文件为空,它打印为nil。评论中有更多信息,我不确定这里问题的原因是什么
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()
答案 0 :(得分:2)
因为你没有在main中引发错误,你只需返回一个错误字符串,所以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
会有其他信息,但不会等同于err
功能的error
。