apolloxlua標準庫require函式說明

鍾元大老爺發表於2018-08-28

使用方式

require(“檔案地址”)

在apollox物理設計上,支援lua的require模組方式,require方法可以在web模式和tool方式使用。 本文簡單介紹一下,在web模式下的配合vfs的使用。

require的具體細節和lua的實現方式類似, 模組作為程式的最小單元存在,模組與模組之間的關係,應該是隔離的。 在web模式下使用vfs組織模組查詢的路徑。

使用require在某種情況下會有限制,他們分別是如果模組的語法存在錯誤,將無法交織到模組的程式碼丟擲錯誤。 如果vfs裡並沒有該模組的平坦模式的程式碼, 會丟擲錯誤。如果vfs配置了baseURL,一般vfs在記憶體無法查詢到該檔案將會根據baseURL的路徑進行遠端載入該模組。

一個簡單示例的vfs的檢視

輸入圖片說明

lua_module.lua 的程式碼如下



--請注意這個程式碼在web console示例程式中是無法執行的。
--這是一個lua的new模組,module case 裡使用

local m = {}

local hellow  = function () 
    print("hellow, i am a module method");
end

m.hellow = hellow;

return m;


lua_duplicatedef.lua 的程式碼如下


--請注意這個程式碼在web console示例程式中是無法執行的。
--這是一個lua的new模組,module case 裡使用

local other = require("build/lua_module.lua")
local m = {}

local hellow  = function () 
    print("hellow, i am duplicate def");
end

m.hellow = hellow;
m.other  = other.hellow;
return m;

module include case 的程式碼如下

//////////
/// 模組測試
/////////
var module = require("build/lua_module.lua");

if(module) {
    module.hellow();
}

var module2 = require("build/lua_duplicatedef.lua");

if(module) {
    module2.hellow();
    module2.other();
}

執行結果:

輸入圖片說明


相關文章