Your advice on Lua code generation

I’m considering generating Lua code as a way of reducing boilerplate and the errors introduced when writing it. Are you employing code generation in your project, and if so, what’s the setup that have worked best for you?

Example use-case
I have a number of different entity types in my game, such as tile, building, enemy spawner, idling enemy, and attacking enemy. For each type, I have a create and a destroy function. Additionally, I have functions to transform an instance from one type to another, e.g. transform_idle_enemy_to_attacking_enemy. As you can imagine, adding new types and modifying existing ones quickly becomes tedious and error-prone.

In the abstract, it would be rather straightforward to define all entity types and their properties, which transformations are allowed, and then generate the Lua code for the above functions.

Possible solutions
One solution would be to write a Python/shell/whatever script to do what I need. What I’m somewhat concerned about is that with time I might end up with a lot of code generation scripts that all work differently, and maintaining them would become a hassle.

I took a quick look at TypeScriptToLua. While it exposes many hooks, it doesn’t seem like it really fits my use-case.

I didn’t find any language-agnostic code generation libraries or frameworks when I did a search. But it seems like a common enough task that there should be something out there. Do you have any recommendations?

Defold defines a transpiler API for third-party languages/file formats that may be transpiled into Lua. Unfortunately, there is not a lot of documentation on the matter. You can check out an example extension-teal that uses the API to define a transpiler for teal files.

2 Likes