尝试在file:write处索引本地'file'(零值)

Ben*_*ack 4 lua

我是lua脚本的新手,我开始创建并使用此脚本将文本写入Lua文件:

A = "Hello"
local file = io.open ('test.txt',"w")
file:write(A)
file:close()
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

:3尝试索引本地'文件'(零值)

这有什么不对?

P/s:我用CHDK在相机上运行这个lua.

Odo*_*oth 9

如果无法打开文件,io.open将返回nil.您可以检索错误消息:

A = "Hello"
local file, err = io.open ('test.txt',"w")
if file==nil then
    print("Couldn't open file: "..err)
else
    file:write(A)
    file:close()
end
Run Code Online (Sandbox Code Playgroud)

见:http://www.lua.org/pil/21.2.html