SIMION® Industry standard charged particle optics simulation software.
About | Documentation | Community/Support | Downloads | Ordering

Info: Lua Cookbook

From SIMION

This page contains examples of common tasks performed in Lua under SIMION 8.0.

Loading data into an array from a file

Method 1

test.dat:

return {
  3, 1, 4,
  1, 5, 9
}

test.lua:

local array = dofile("test.dat")
-- print contents
for i,v in ipairs(array) do
  print(i,v)
end

result:

1       3
2       1
3       4
4       1
5       5
6       9

Above, test.dat is actually a Lua program itself that returns an array. The test.lua program runs the test.dat program to obtain the array it returns.

Method 2

test2.lua:

function read_file_numbers(filename)
  local array = {}
  local f = assert(io.open(filename))
  while true do
    local v = f:read("*number")
    if not v then break end
    table.insert(array, v)
  end
  f:close()
  return array
end

function write_file_numbers(filename, array)
  local f = assert(io.open(filename, 'w'))
  for _,v in ipairs(array) do
    f:write(v, ' ')
  end
  f:close()
end

-- Create array in memory
local t = {3,4,5,2,5,3e20,10,2,7,-0.3}

-- Write arry to file
write_file_numbers("test2.dat", t)

-- Read array back from file
local t2 = read_file_numbers("test2.dat")

-- check that array is unchanged
for i=1, #t do
  assert(t[i] == t2[i])
end
print("ok")
Any comments on this web page? (will be sent to SIS)
[Optional] Your name: email: phone/fax:
(c) 2003-2006 Scientific Instrument Services, Inc. (SIS). Contact SIS.