Refactor lua code