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

API with metatable

Started by Sebra, 27 February 2016 - 07:43 AM
Sebra #1
Posted 27 February 2016 - 08:43 AM
While Dan200 in the process of changing and we all can test new beta I want to ask for a way to add metatable to loaded API.
Any way would be good. Even that simple way in spoiler. It allows API to return it's table directly but not forces to change any existing API.

Spoiler

local tAPIsLoading = {}
function os.loadAPI( _sPath )
	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 = _G } )
	local fnAPI, err = loadfile( _sPath, tEnv )
	if not fnAPI then
		printError( err )
		tAPIsLoading[sName] = nil
		return false
	end
	local ok, ret = pcall( fnAPI )
	if not ok then
		printError( ret )
		tAPIsLoading[sName] = nil
		return false
	end
	if ret ~= nil and type(table)=="table" then
		_G[sName] = ret
	else
		local tAPI = {}
		for k,v in pairs( tEnv ) do
			if k ~= "_ENV" then
				tAPI[k] =  v
			end
		end
		_G[sName] = tAPI  
	end

	tAPIsLoading[sName] = nil
	return true
end

Dan200, please answer.
Is API metatable not wanted for any reason?
Is my example bad?
Would you add any other way for it?
Creator #2
Posted 27 February 2016 - 10:23 AM
Just use setmetatable:


setmetatable(API,table) --don't actually call it table baecause it will cause issues.

Metatables are not bad ina any way.

Why do you think someone is against them?
Edited on 27 February 2016 - 09:26 AM
Sebra #3
Posted 27 February 2016 - 12:19 PM
Current way of loading API copies API content to new table after API loaded. So there is no way for API to add metatable to own table.