Gideros Studio has powerful built-in feature: Lua code preprocessing with macros which is based on great work of Steve Donovan: https://github.com/stevedonovan/LuaMacro
You can use built-in macros or write your own. In this tutorial I will show you how to use built-in '@def'
NOTE: To enable preprocessing you need to turn on 'Macro Support' in Settings of Gideros Studio first.@def
macro has two syntax forms:
<a href="/profile/def">@def</a> name body --> oneline
<a href="/profile/def">@def</a> (name --> multiline
Let's start with simple example:
<a href="/profile/def">@def</a> HELLO "Hello, World!"
print(HELLO) --> Hello, World
We are defined a simple constant. Why constants are good? Because they have no performance overhead as variables have and they also don't occupy valuable variable space.
More complex example:
<a href="/profile/def">@def</a> CUBE(x) ((x)*(x)*(x))
local n = 5
print(CUBE(n)) --> 125
Instead of 'function CUBE(x) return x * x * x end' (which is expensive in this case) that macro-function will replace all xs with any given expression i.e. will be unrolled to 'n * n * n'.
Unlike C LuaMacros are lexically scoped and their expansion controlled by Lua itself:
<a href="/profile/def">@def</a> x 1
<a href="/profile/def">@def</a> x 2
print(x) --> 2
print(x) --> 1
Another macro-function example:
<a href="/profile/def">@def</a> (complain(msg,n)
for i = 1,n do
complain("Hello!", 5) --> print "Hello" 5 times
As you can see @def
macro is well suited to inline optimized Lua code. It's also well known to programmers because of C 'define' directive which is frequently used.
You can find other macros in 'Gideros/Tools/luamacro/macro/' folder and if you want to write new macro you must put it here. To require them in your code use @require
<a href="/profile/require">@require</a> "do"
y = 0
<a href="/profile/do%28i">@do(i</a>, 1, 10, y = y + 1)