lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


RLake@oxfam.org.pe wrote:
 > local arrayFile = "Array.txt"
 > local array = { 1, 5, 12.3, 0.25, -45.01, 7 }
 > local f = io.open(arrayFile, "w")
 > f:write("return {\n")
 > for i, v in ipairs(array) do
 >   f:write("[" .. i .. "]=" .. v .. ",")
 > -- Add \n if you want the file to be readable by humans
 > end
 > f:write("}\n")
 > f:close()

even shorter, although it uses more memory:

function dumpArray(file, array)
  local f = assert(io.open(file, "w"))
  assert(f:write("return {", table.concat(array, ","), "}"))
  assert(f:close())
end

I forgot that concat can use a separator...
Note that if my routine was written with pairs instead of ipairs, it will works even if there are holes in the array...
Althought data will be no longer in increasing key values.

--
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/ (outdated)
http://philho.multimania.com (in French, for files to download)
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--