lua-users home
lua-l archive

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


On 05/25/2017 09:36 AM, Christopher Tallman wrote:
> Hi, I'm trying to accomplish a string find/replace on a Lua file,
> essentially updating the values stored in a table with new values,
> while preserving the structure, layout, and comments of the file (I
> don't want to just serialize the table, since that would drop
> formatting and comments).
> 
> For example, let's say I have a file Lua file containing the following:
> 
> <code>
> -- Range descriptions
> ranges = {
>   [1] = {0, 100}, -- primary
>   [2] = {101, 500}, -- secondary
>   [3] = {500,1000}, -- final range
> }
> </code>
> 
> I'm trying to write a lua program that will read in this file and the
> values in the subtables with new values and write the file back out,
> preserving the rest of the file.  I'm pretty sure this is a simple
> problem to solve with LPeg, but I've never used it before.  I could
> probably get this working with plain regex, but I would like to learn
> something new in the process and try doing it with LPeg.  Any advice
> or pointers on how I can get this to work?  Good resources for someone
> unfamiliar with PEG?
> 
> Many thanks,
> Chris
> 

AFAIK there are no currently public tools that can do this. There are
some custom lexers/parsers but all they drop whitespaces.

Some time ago I wrote parser-based Lua code reformatter. Parser can be
tuned to keep comments and whitespeces in returned structure. But your
code for processing such structure will be quite complex.

Probably the simplest and fastest way for your case is just use gsub, as
Luiz recommended.

-- Martin