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

Lua: API deprecation (See related posts)

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

function deprecate(o,name,instead)
	local msg = "%sWarning, deprecated feature "..(name and ("'"..name.."' ") or "").."in use."..(instead and ("  Use '"..instead.."' instead.") or "")
	if(type(o) == "table") then
		return setmetatable({},{__index = function (t,k)
				local _,callpoint = pcall(function() error("",4) end)
				print(string.format(msg,string.gsub(callpoint,"(^w%*%.%w*%:%d+)","%1")))
				return o[k]
			end,
			__newindex = function (t,k,v)
               	local _,callpoint = pcall(function() error("",4) end)
				print(string.format(msg,string.gsub(callpoint,"(^w%*%.%w*%:%d+)","%1")))
				o[k] = v
				return o[k]
			end
		})
	elseif(type(o) == "function") then
		return function(...)
			local _,callpoint = pcall(function() error("",4) end)
			print(string.format(msg,string.gsub(callpoint,"(^w%*%.%w*%:%d+)","%1")))
			return o(unpack(arg))
		end
	end
end


Example Usage:
Ace = {}

function Ace:print(msg)
	print(msg)
end

function foo()
	print("FOO!")
end
ace = deprecate(Ace,"ace","Ace")
FOO = deprecate(foo,"FOO","foo")

FOO()
ace:print("moo")


Output of Example Usage:
./deprecate.lua:38: Warning, deprecated feature 'FOO' in use.  Use 'foo' instead.
FOO!
./deprecate.lua:39: Warning, deprecated feature 'ace' in use.  Use 'Ace' instead.
moo

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts