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

Please insert __pairs and __ipairs in metatables

Started by Sewbacca, 23 May 2016 - 03:10 PM
Sewbacca #1
Posted 23 May 2016 - 05:10 PM
Here the Code (untested):


-- Lists

local metatables = {}  -- Save all metatables (it isn't RAM costly)

-- Save natives

local nativeSetMetatable = setmetatable
local nativePairs = pairs
local nativeiPairs = ipairs

-- Overwrite origins

setmetatable = function(tab, mt)
  local ok, err = pcall(nativeSetMetatable, tab, mt) -- Error providing
  if ok then
	metatables[tab] = mt -- If no error, then save the table and metatable
  else
	return error(err) -- If an error occur, then report it
  end
end

pairs = function(...)
  local tArgs = {...}
  for _, var in ipairs(tArgs) do
	<ERROR PROVIDING>
  end

  if metatables[tArgs[1]] and type(metatables[tArgs[1]].__pairs) == 'function' then -- Check, if the table have an metatable and if __pairs is a function
	return metatables[tArgs[1]].__pairs(...) -- If true, then call pairs
  end
  return nativePairs(...) -- Call native pairs
end

ipairs = function(...)
  local tArgs = {...}
  for _, var in ipairs(tArgs) do
	<ERROR PROVIDING>
  end

  if metatables[tArgs[1]] and type(metatables[tArgs[1]].__ipairs) == 'function' then -- Check, if the table have an metatable and if __ipairs is a function
	return metatables[tArgs[1]].__ipairs(...) -- If true, then call pairs
  end
  return nativeiPairs(...) -- Call native pairs
end

-- End
Edited on 23 May 2016 - 03:12 PM
KingofGamesYami #2
Posted 23 May 2016 - 05:27 PM
Link
Sewbacca #3
Posted 25 May 2016 - 07:24 PM
???