項(xiàng)目客戶端腳本全面升級(jí)lua5.2 這是自06年后最大的一次主干更新, 帶來(lái)的機(jī)制, 函數(shù)變化也是非常不錯(cuò)的
1. 去掉了全局性質(zhì)的setfenv/getfenv系列函數(shù), 語(yǔ)言層面提供_ENV語(yǔ)法糖, 這東西跟:操作符一樣, 只存在于編譯期.
官方建議自己實(shí)現(xiàn)module/require/package機(jī)制, 畢竟原生這套機(jī)制實(shí)現(xiàn)太弱智了..
2. 提供了無(wú)符號(hào)訪問(wèn)函數(shù)
3. 更多的lua api變化. 如果想兼容lua5.1的寫(xiě)法, 可以參考luabridge內(nèi)LuaHelpers.h的實(shí)現(xiàn)
以下是本人使用lua5.2實(shí)現(xiàn)的一套package機(jī)制, 供大家參考
package = {}
-- 讀取標(biāo)記
package.loaded = {}
-- 搜索路徑數(shù)組
package.path = {}
package.access =
{ ["string"] = string,
["print"] = print,
["table"] = table,
["assert"] = assert,
["error"] = error,
["pairs"] = pairs,
["ipairs"] = ipairs,
["tonumber"] = tonumber,
["tostring"] = tostring,
["type"] = type,
["math"] = math,
}
local function getreadablepath( name, pathlist )
for _, path in ipairs(pathlist) do
local fullpath = path .. "/" .. name .. ".lua"
local f = io.open( fullpath )
if f then
f:close()
return fullpath
end
end
return nil
end
function package.import( name )
-- 已經(jīng)讀取的直接返回
local existedenv = package.loaded[name]
if existedenv then
return existedenv
end
local access = package.access
-- 設(shè)置訪問(wèn)控制權(quán)限
local meta =
{ __index = function( tab, key )
-- 優(yōu)先取包的空間
local v = rawget( tab, key )
if v then
return v
end
-- 找不到時(shí),從可訪問(wèn)的權(quán)限表中查找
return access[key]
end,
}
-- 初始化一個(gè)包的全局環(huán)境, 并設(shè)置訪問(wèn)方法
local env = setmetatable( {} , meta )
--
local readablepath = getreadablepath( name, package.path )
if not readablepath then
error(string.format("package '%s' not found \n%s", name, table.concat( package.path, "\n" ) ) ) end
local func = loadfile( readablepath, "bt", env )
if type(func) ~= "function" then
return nil
end
-- 設(shè)置標(biāo)記
package.loaded[name] = env
-- 執(zhí)行全局空間
func( )
return env
end
package.path = {"E:/Download/t"}local m = package.import "m"
m.foo()
以下是m模塊(m.lua)的內(nèi)容
function foo( )
print("轉(zhuǎn)載注明: 戰(zhàn)魂小筑 http://m.shnenglu.com/sunicdavy", io ) end
測(cè)試結(jié)果中, io打印出nil, 顯示權(quán)限已經(jīng)被控制住
本package設(shè)計(jì)比原生package更靈活, 更強(qiáng)大