Skip to content

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

@ayoubfaouzi

Description

@ayoubfaouzi

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions