Code Templates

Code templates are useful when you have snippets of code that you want to reuse. You can use them for commonly used constructs like for loops, if statements, function definitions, or even non-code stuff such as license headers and comments. Code templates are also smart, it uses a templating engine that allows you to specify wildcards that automatically update as you type, much like the instant renamer feature. Lets go through a few examples.

First we need to open up the code templates window. You can do this from the Preferences on Mac or Tools->Options on Windows and Linux.

Basic code template overview

Once you opened that make sure that the Lua language is selected. The abbreviation is what we type to invoke the code template so make it something convenient. Lets create a new code template and call it func

New Code Template

Now just paste the following lua code snippet into the Expanded Text tab:

function myfunction()

So your screen would end up looking like this:

Example plain template

You can give it a description if you like. Now press Apply to save the template and return to the options menu, it is a on-modal dialog so it can remain open. Now here is the important part, quickly type func and press the tab key quickly. You must execute the abbreviation without any errors, typing funk Backspace + c + tab will not work. After executing the code template, your editor should look like this:

template with variable

Thats great! Now we can really save lots of typing. Now lets make the function name editable. By using ${var_name} template tags you can create dynamic code templates. Lets change our code template to this:

function ${function_name}()

Now when we expand the code template we will be able to edit the name without having to select anything. Press Enter when you are finished editing. Notice how the cursor ends up at the end keyword and you would have to use the keypad to actually edit the function body. Lets fix that by using the ${cursor} tag:

function ${function_name}()

Now when you invoke the code template you can edit the name like usual but after pressing Enter the cursor will be inside the body of the function and you can continue coding without taking your hands off the home keys.

Thanks for reading this tutorial. If you get stuck or have any questions please do not hesitate to ask below.