Using macros in the source code of Apollo xlua

Posted by FlipinMonkeyPie on Tue, 07 Jan 2020 07:45:08 +0100

This article explains how to use macros in two modes. First, there are two modes under Apollo Lua, one is web mode and the other is tool mode. In the web mode, we can use it on the browser side, but there are some limitations. For example, some native APIs cannot be used, such as ngx, redis and mysql. For example, please see web console example . In the other tool mode, the tool mode has no restrictions.

We use conditional compilation when dealing with problems in a certain field. Conditional compilation reduces the size of our code and increases program flexibility. For example, this example shows how to use:

The syntax used by macros:

1 macro notes

{% if  SCRIPT  == "lua" then %}
     return exports.GetValueByType (eax.value);
{% end %}

{% if  SCRIPT  == "neko" then %}
     return exports.GetValueByType (eax.value);
{% end %}


{% if  SCRIPT  == "c" then %}
     return exports.GetValueByType (eax.value);
{% end %}

2 inline macro

 {-inline_listense-} 
    Copyright (c) 2018 agent.zy@aliyun.com
 {-inline_listense-}

Inline in the code this syntax will output different inline macro to the specified location

3 function definition

 {%   
    local lua\_member\_call    ="{{item}}:{{item1}}({{item2}})"
    local lua\_string\_add_val ="\\"{{item}}\\" .. {{item2}}"
    local lua\_string\_add_string ="\\"{{item}}\\" + \\"{{item2**}}\\""
 %}

4 inline function

{-inline_max-}
function  max (a, b) {
return a>b;
}
{-inline_max-}

How to use our defined inline functions

{blocks.inline_max}

5 replacement mode

{% 
local string_macro ="\\"{{item}}\\""
%}
{\* MACRO(string_macro)(context) *}
{\* MACRO(string_macro){ item = "string-macro-context" } *}

Example:

{-inline\_esprima\_parse-}
    var options = {
        attachComment: false,
        range: false,
        loc: false,
        sourceType: "script",
        tolerant: true
    };

    options.tokens = false;
    var result = exports.esprima.parse(buff, options);

{-inline\_esprima\_parse-}

/////
/////Generate code 
/////
{-inline\_generate\_code-}
 exports.lexerGenerateCode(result);
{-inline\_generate\_code-}


////
////Generate bytecode
////

{-inline\_generate\_mid-}
 exports.lexerGenerateMidCode(result);
{-inline\_generate\_mid-}



{% if  SCRIPT  == "lua" then %}
exports.Main = function (buff) {
    {% if  DEBUG  then %}
        console.log("lua mode.")
    {% end %}
    ///Generate ast resolution
    {\*blocks.inline\_esprima\_parse\*} 
    //Generate code
    {\*blocks.inline\_generate\_code\*}       
}
{% end %}


{% if  SCRIPT  == "c" then %}
exports.Main = function (str) {
    {% if  DEBUG  then %}
        console.log("c mode.")
    {% end %}
    {\*blocks.inline\_esprima\_parse\*}
    {\*blocks.inline\_generate\_code\*} 
}
{% end %}

Finally, when using, the web mode does not need to be processed. In the tool mode, please use luadef tools Precompile.

Topics: Redis MySQL