2013-05-01 2 views
1

상황 :루아 스크립트 오류

특정 파일에 센서 값인 데이터 레코드를 저장하려고합니다. 이 라인에서

코드입니다 ..

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

:

내가 그것을 어떻게

"attemp to index global 'filehandle' (a nil value)" 
을 를 해결할 수 :

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

는 오류가 발생합니다?

답변

2

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 

당신은 또한 다음과 같은 루아 관용구를 사용할 수

로는 :

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

이 같은 행동을 할 것입니다. assert의 첫 번째 인수가 nil이면 두 번째 인수 (io.open의 두 번째 반환 값이 인쇄되고 첫 번째 인수가 nil이 아닌 경우

이 반환됩니다.