Lua脚本错误

情况:

我想将传感器的数据值保存在某个文件中。

代码如下:

--Header file
require("TIMER")
require("IPBOX")
require("ANALOG_IN")
require("LOG")

function OnExit()
print("Exit code...do something")
end

function main()
timer = "Timer"
local analogsensor_1 = "AIR_1"
local analogsensor_2 = "AIR_2"
local timestr = os.data("%Y-%m-%d %H:%M:%S")

-- open the file for writing binary data
local filehandle = io.open("collection_of_data.txt", "a")

while true do
    valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
    valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);

    if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then

        -- save values of sensors
        filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2) , "\n");

        -- save values using rolling log appender:
        LOG.log_event( ScenarioLoggerDevicenameInDeviceList, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2), "any other string you wish to add", "etc", "etc")
        LOG.log_event( ScenarioLoggerDevicenameInDeviceList, " -The Value of the Sensors: ", tostring(valueOfSensor_1))
        print("Hello3" .. valueOfSensor_1)
    end

TIMER.sleep(timer, 500)
end

-- close the file
filehandle:close()

end

print("start main")
main()

在这一行:

filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2) , "\n");

我得到了一个错误:

"attemp to index global 'filehandle' (a nil value)"

我该如何解决?

点赞
用户1633117
用户1633117

io.open 如果无法打开文件,将返回 nil。这可能是由于 "文件未找到"、"权限被拒绝" 或其他原因。为了找出问题所在,io.open 有第二个返回值,允许您检查错误(实际上,它甚至返回第三个值,即一个错误代码整数 - 但其含义取决于系统)。

将以下更改:

local filehandle = io.open("collection_of_data.txt", "a")

改为

local filehandle, message = io.open("collection_of_data.txt", "a")
if not filehandle then
    print(message)
end

您还可以使用以下 Lua 习惯用法:

local filehandle = assert(io.open("collection_of_data.txt", "a"))

这会做同样的事情。如果 assert 的第一个参数是 nil,则将打印第二个参数(io.open 的第二个返回值)。如果第一个参数不是 nil,它将被简单地返回。

2013-05-01 13:06:11