lua-users home
lua-l archive

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


On Fri, 12 Mar 2004, JK wrote:

> 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
> ...?

> Is it possibile to do this elegantly in just 8 lines in Lua?

If you're using the stdlib libraries from the lua-users stdlib project,
this is a matter of:

t = {1,2,3,4,5}
h = io.open("foo","w")
h:write(pickle(t))
h:close()

h = io.open("foo", "r")
t = eval(h:read("*a"))
h:close()

The two useful functions that you get from the libraries here are pickle
and eval. The latter is trivial:

-- @func eval: Evaluate a string
--   @param s: string
-- @returns
--   @param v: value of string
function eval (s)
  return loadstring ("return " .. s)()
end

The former is rather more involved, and currently doesn't work for
recursive tables (doesn't sound as though it's a problem in your case). In
any case, I've already added a tostring that works on recursive tables, so
rewriting pickle in the same way wouldn't be a problem.

-- 
http://www.mupsych.org/~rrt/ | plagiarism, n.  the mind burgles