lua-users home
lua-l archive

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

JK wrote:
I found this question with many answers regarding the language Ruby. /*
After I do bunch of computations and create a huge array with bunch of
numbers, I like to use the already-computed array in another program
rather than re-computing it each time I run the program. How can I
save the array object in one program and read it from another program
in Ruby?
and I found this answer the simplest one:

You can use marshalling:

array = ..."array", "wb") do |f|
  Marshal.dump(array, f)

To reload:

array = nil"array", "rb") do |f|
  array = Marshal.load(f)

Now, I need the same thing in Lua. Is it possibile to do this elegantly in just 8 lines in Lua?

I can do that in 1 line only, but it will not be very readable...
A number of methods to serialize tables have been given here over the years, none perfect because Lua can store all kind of strange data (userdata for example) as keys or values.

Since you have very simple needs (manage a simple array of numbers only), I can give a very simple code:

local arrayFile = "Array.txt"
local array = { 1, 5, 12.3, 0.25, -45.01, 7 }
local f =, "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

And read back the values with:

local array = dofile(arrayFile)

Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist (outdated) (in French, for files to download)