我有下面的代碼片段設置一個全球性的要求
function initializeWorld()
_G.require = function(name)
if package.loaded[name] == nil then
local result, err = external.MyAPIEndpoint:LUAInclude(name .. '.lua')
if err == nil then
if result ~= nil then
package.loaded[name] = result
else
package.loaded[name] = true
end
return package.loaded[name]
else
local errTxt = err .. "\r\n" .. debug.traceback()
error(errTxt, 1)
end
else
return package.loaded[name]
end
end
helloWorld = require ("helloWorld")
print(helloWorld.welcome())
end
function initializeUniverse()
_G.require = function(name)
if package.loaded[name] == nil then
local result, err = external.MyAPIEndpoint:LUAInclude(name .. '.lua')
if err == nil then
if result ~= nil then
package.loaded[name] = result
else
package.loaded[name] = true
end
return package.loaded[name]
else
local errTxt = err .. "\r\n" .. debug.traceback()
error(errTxt, 1)
end
else
return package.loaded[name]
end
end
helloUniverse = require ("helloUniverse")
print(helloUniverse.welcome())
end
正如你可以看到global requires
在兩個不同的地方使用。一次在initializeWorld
,另一個在initializeUniverse
我可以對代碼進行修改,使其只加載一次嗎?
感謝
將它從最後調用的哪個函數中刪除?如果它是競爭條件,請在外部定義它(可能有條件地將它加載到兩者中)。 – Oka
'local local_require = function(name)... end;函數initializeWorld()_G.require = local_require; ... 結束;函數initializeUniverse()_G.require = local_require; ...結束;' –