py-lua-parser icon indicating copy to clipboard operation
py-lua-parser copied to clipboard

Question: Help with an example of removing a statement and re-writing the AST

Open ayoubfaouzi opened this issue 8 months ago • 0 comments

Hello,

Given the lua source code below:

local mytable = {}

mytable.windows = 2
mytable.linux = 3

I am trying to remove this assignment (mytable.linux = 3) from the code so I wrote:

    tree = ast.parse(lua_src)

    filtered_body = []
    for node in ast.walk(tree):
        skip = False
        if isinstance(node, astnodes.Assign) and isinstance(node.targets[0], astnodes.Index):
            table = node.targets[0].value.id
            key = node.targets[0].idx.id
            if table == "mytable" and key in ("windows", "linux"):
                if key != "windows":
                    # Skip the OS section not matching target
                    skip = True
        if not skip:
            filtered_body.append(node)

    # Create a new chunk (program root)
    new_chunk = astnodes.Chunk(body=filtered_body)

    # Generate Lua code from AST
    new_source = ast.to_lua_source(new_chunk)

    print(new_source)

But I am not getting what I want, can you please help.

ayoubfaouzi avatar Apr 29 '25 07:04 ayoubfaouzi