My api file:
x = 2
setX = function(value) x = value end
getX = function() return x end
Main script:
os.loadAPI('myapi')
print(myapi.x) -- 2
myapi.setX(3)
print(myapi.x) -- 2
print(myapi.getX()) -- 3
This happens because globals are copied into the API object, while the functions still refer to the original variable. The solution here is to use metatables, to proxy access to globals into the API table. Here's some code that fixes the important bit:
-- set up a function environment with access to _G
local tAPI = {}
local tEnv = setmetatable({}, {
__index = function(_, k, v)
if tAPI[k] ~= nil then
return tAPI[k]
elseif k == "module" then
return tAPI
else
return _G[k]
end
end,
__newindex = tAPI
})
This also allows modules to reference themselves with the global `module`, allowing modules to be renamed more easily.The full code can be found on github. I've made a few more changes:
- If a module errors, it doesn't prevent it being loaded in future
- Option to force module reloading
- Distinction between loading and loaded