[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Reading & writing an array of numeric data
- From: Philippe Lhoste <PhiLho@...>
- Date: Fri, 12 Mar 2004 15:28:35 +0100
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 = ...
File.open("array", "wb") do |f|
Marshal.dump(array, f)
end
To reload:
array = nil
File.open("array", "rb") do |f|
array = Marshal.load(f)
end
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 = 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()
And read back the values with:
local array = dofile(arrayFile)
--
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
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)
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--