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/LuaMacroYou can use built-in macros or write your own. In this tutorial I will show you how to use built-in '
@def' macro.
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="https://forum.giderosmobile.com/profile/def" rel="nofollow">@def</a> name body --> oneline
<a href="https://forum.giderosmobile.com/profile/def" rel="nofollow">@def</a> (name --> multiline
body
) |
Let's start with simple example:
<a href="https://forum.giderosmobile.com/profile/def" rel="nofollow">@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="https://forum.giderosmobile.com/profile/def" rel="nofollow">@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="https://forum.giderosmobile.com/profile/def" rel="nofollow">@def</a> x 1
do
<a href="https://forum.giderosmobile.com/profile/def" rel="nofollow">@def</a> x 2
print(x) --> 2
end
print(x) --> 1 |
Another macro-function example:
<a href="https://forum.giderosmobile.com/profile/def" rel="nofollow">@def</a> (complain(msg,n)
for i = 1,n do
print msg
end
)
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="https://forum.giderosmobile.com/profile/require" rel="nofollow">@require</a> "do"
y = 0
<a href="https://forum.giderosmobile.com/profile/do%28i" rel="nofollow">@do(i</a>, 1, 10, y = y + 1)
print(y) |
Comments
Likes: antix
https://deluxepixel.com
Doesn't seem to work at all with ZeroBrane Studio
Likes: antix
https://deluxepixel.com
When would this be used practically, in a game? Could it replace local variables that don't change? What kind of performance boost will this give?
eg
It also uses one less variable than
Likes: antix, totebo
https://deluxepixel.com