lua-users home
lua-l archive

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


On 24 Nov 2016 06:23, "David Given" <dg@cowlark.com> wrote:
>
> I want to write out strings to a file and read them back in again, in an
> ASCII-safe way. I'm writing them out with string.format("%q"), because
> it's cheap and easy[*], but now I need to read them back in again.
>
> Actually going through the string and parsing the escapes seems like a
> lot of work. A faster but much scarier alternative is to wrap the string
> with 'return (<string>' and compile and execute it in a restricted
> environment.
>
> Given that the interpreter already contains code to safely turn an
> escaped string into a Lua string, there must be a better way --- what is it?

I've been thinking about this thread for the last few days.
I came to the conclusion that the best API would be a way to access
the 'constants' used by a given function via a debug.* api.
I wrote a lua patch for how I think it might look:
https://github.com/lua/lua/compare/master...daurnimator:debug.getconstant?expand=1

With this patch, you might safely serialise/unserialise like so:

mystr = "foo"
serialised = string.format("return %q", mystr)
debug.getconstant(load(serialised, nil, "t", nil), 1) --> foo