You would be better served with an external script driving the PM client. I tried to implement this sort of thing in LUA and quickly ran into limitations. I ended up using the client as a backend, which is trivial and lets you do anything you can do on the command line, but in an automated way
If you want to see how that goes, look at the client/pyscripts/theremin.py script in the PM3 repo - which I wrote.