jung hur
jung hur

Reputation: 91

Lua Script Error

Situation:

I want to save the record of a data which is a value of the sensor in the certain file.

Code is..

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

In this line:

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

I get an error:

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

How can I fix it?

Upvotes: 1

Views: 590

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

io.open returns nil if it cannot open the file. This can be due to "file not found", "permissions denied" and maybe other reasons. To figure out the problem, io.open has a second return value, which lets you inspect the error (in fact, it even returns a third value, which is an error-code integer - but its meaning is system dependent).

Change:

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

to

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

You can also use the following Lua idiom:

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

This will do the same. If the first argument to assert is nil, then the second argument (the second return value of io.open will be printed. If the first argument is not nil, it will simply be returned.

Upvotes: 2

Related Questions