apolloxlua 源碼內使用macros

本文講解如何在兩種模式下使用macros,首先在apolloxlua下有兩種模式, 一種是 web模式另外一種是工具模式。 web模式下咱們能夠在瀏覽器端來使用,可是有一些限制, 就是好比說某些native的api是沒法使用的, 好比說ngx,redis,mysql這種。示例請看 web控制檯示例 。而另一種工具模式, 工具模式沒有使用限制。mysql

咱們在處理某個領域的問題時候, 會用到條件編譯。 條件編譯會減小咱們代碼的體積和增長程序的靈活性。 好比這個示例中展現瞭如何使用:git

macros 宏使用的語法:

1 宏註釋

{% 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 macro 輸出到指定位置web

3 函數定義

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

4 內聯函數

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

如何使用咱們定義的內聯函數redis

{blocks.inline_max}sql

5 替換模式

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

例子 :api

{-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-}

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


////
////   生成字節碼
////

{-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 %}
    ///生成ast解析
    {\*blocks.inline\_esprima\_parse\*} 
    ///生成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 %}

最後在使用的時候, web模式不須要處理, 在tool模式下請使用 luadef工具 進行預編譯。瀏覽器

相關文章
相關標籤/搜索