I am having a problem with command
local f = (io.open(‘test.txt’, “r”) ~= nil)
according to documentation this should return true if file exists and false it doesn’t.
BUT in ardupilot LUA it returns always true even if file doesn’t exist, I investigated more and I saw that it returns always a file and an adress not matter what, like it creates file, but I use only parameter “r”.
Can you please help me ? I need to check if the file exists in order to avoid overwrite data but create a similar like test_2.txt
That’s a problem of an older ArduPilot version I encountered also. It helps to update to latest.
This is how I have been overcomming the problem, just try and read the first character from the file.
-- search for a index without a file, this stops us overwriting from a previous run
local index = 0
while true do
file_name = string.format('Particle %i.csv',index)
local file = io.open(file_name)
local first_line = file:read(1) -- try and read the first character
if first_line == nil then
index = index + 1
I installed 4.3.7 version (the latest in “stable” folder of server) but it did not solve the problem.
Wow, that was fast response by Yuri_rage. Thank you Pete the "detour’ way works, but still I was curious what was happening.
The Lua engine used by ArduPilot is imperfect (and constantly improving, but you shouldn’t chase the latest dev versions for fixes unless you know exactly what you’re doing).
Stick with latest stable and follow Pete’s advice.
With “latest” that is working correctly:
-- count available missions Mission#x.waypoints
num_files = 0
while true do
file = io.open(string.format('%s/%s', sub_dir, string.format('%s_%s%d.%s', SCRIPT_NAME, MISSION_FILE_PREFIX, num_files, FILE_EXTENSION)))
if file then
num_files = num_files + 1
send_msg(INFO, string.format('%d missions found', num_files))
So the problem is still solved.
But you should do like
@iampete and @Yuri_Rage told you.
But be aware that the script by Pete will produce an error if you use the corrected version some day.