Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Lua: API deprecation

What follows is Tem's code to deprecate an API function or table in Lua.

   1  function deprecate(o,name,instead)
   2  	local msg = "%sWarning, deprecated feature "..(name and ("'"..name.."' ") or "").."in use."..(instead and ("  Use '"..instead.."' instead.") or "")
   3  	if(type(o) == "table") then
   4  		return setmetatable({},{__index = function (t,k)
   5  				local _,callpoint = pcall(function() error("",4) end)
   6  				print(string.format(msg,string.gsub(callpoint,"(^w%*%.%w*%:%d+)","%1")))
   7  				return o[k]
   8  			end,
   9  			__newindex = function (t,k,v)
  10                 	local _,callpoint = pcall(function() error("",4) end)
  11  				print(string.format(msg,string.gsub(callpoint,"(^w%*%.%w*%:%d+)","%1")))
  12  				o[k] = v
  13  				return o[k]
  14  			end
  15  		})
  16  	elseif(type(o) == "function") then
  17  		return function(...)
  18  			local _,callpoint = pcall(function() error("",4) end)
  19  			print(string.format(msg,string.gsub(callpoint,"(^w%*%.%w*%:%d+)","%1")))
  20  			return o(unpack(arg))
  21  		end
  22  	end
  23  end


Example Usage:
   1  Ace = {}
   2  
   3  function Ace:print(msg)
   4  	print(msg)
   5  end
   6  
   7  function foo()
   8  	print("FOO!")
   9  end
  10  ace = deprecate(Ace,"ace","Ace")
  11  FOO = deprecate(foo,"FOO","foo")
  12  
  13  FOO()
  14  ace:print("moo")


Output of Example Usage:
   1  
   2  ./deprecate.lua:38: Warning, deprecated feature 'FOO' in use.  Use 'foo' instead.
   3  FOO!
   4  ./deprecate.lua:39: Warning, deprecated feature 'ace' in use.  Use 'Ace' instead.
   5  moo
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS