2013-05-01 181 views
1

情況: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)" 

我怎樣才能解決這個問題?

回答

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 

您也可以使用下面的Lua成語:

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

這也將這樣做。如果assert的第一個參數是nil,則會打印第二個參數(第二個返回值爲io.open)。如果第一個參數不是nil,它將被簡單地返回。