This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
クデル's profile picture

Loading API's into a Specific Enviroment

Started by クデル, 29 November 2015 - 01:10 AM
クデル #1
Posted 29 November 2015 - 02:10 AM
Pretty much as the title says, I cloned _G with:
_env = _G
But my program is running in _G still, so I want to load API's into _env without moving from _G.
KingofGamesYami #2
Posted 29 November 2015 - 02:33 AM
That wont clone _G at all, rather it would make _env a pointer to it.

You could make a custom loadAPI function.

Custom loadAPI

local tAPIsLoading = {}
function customLoadAPI( _sPath, _env )
    local sName = fs.getName( _sPath )
    if tAPIsLoading[sName] == true then
        printError( "API "..sName.." is already being loaded" )
        return false
    end
    tAPIsLoading[sName] = true

    local tEnv = {}
    setmetatable( tEnv, { __index = _env } ) --#give it only the stuff in _env
    local fnAPI, err = loadfile( _sPath, tEnv )
    if fnAPI then
        local ok, err = pcall( fnAPI )
        if not ok then
            printError( err )
            tAPIsLoading[sName] = nil
            return false
        end
    else
        printError( err )
        tAPIsLoading[sName] = nil
        return false
    end

    local tAPI = {}
    for k,v in pairs( tEnv ) do
        if k ~= "_ENV" then
            tAPI[k] =  v
        end
    end

    _env[sName] = tAPI   --#instead of _G, put it in _env  
    tAPIsLoading[sName] = nil
    return true
end
Edited on 29 November 2015 - 01:58 AM
クデル #3
Posted 29 November 2015 - 04:04 AM
Thanks, I decided to just take the easy way out by loading APIs within a function set to use the enviroment. :)/>