I am writing a program to find the standard deviation of a data set. I don't have a proper Lua editor so I am testing everything from the interactive interpreter.
In the code below, everything seems to work until I get to the diffsqrd function. After I call this function, the interpreter stops letting me type anything in. I have to close it and start over again. I have tested this function by itself, without the code before it and it works fine.
I tried saving the whole thing as a .lua file and running it with dofile but it did the same thing. I get nothing, and then I can no longer type into the interpreter. What is going on?
--a function to see if a file exists
function file_exists(file)
local f=io.open(file, "r")
if f then f:close() end
return f ~= nil
end
--get all lines from a file, returns an empty
--list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
--Put the .rec file into an array
y_positions=lines_from([[Z:\Octupole stuff\programming\y_p_test.rec]])
--functions to find the standard deviation of an array.
--total, average, difference squared. I stop here because this is the
--minimum code required to cause the problem.
function total(a)
local sum=0
for i,v in ipairs(a) do sum = sum + v
end
return sum
end
function average(a)
if #a==0 then mean=0
else mean=total(a)/#a
end
return mean
end
function diffsqrd(a)
local diff={}
for i in ipairs(a) do
diff[i]=(a[i]-average(a))^2
end
return diff
end
--Use the diffsqrd function on the .rec file.
yd=diffsqrd(y_positions)
print(yd[1])