How do I optimize this script?

You would just have to recalculate the greedy mesh for that specific area when the player mines/places a block. This is how every voxel game including Minecraft does it. Making and optimising a voxel game is a surprisingly complicated topic, I’d recommend you give these a read.