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

About this user

Chris Larson http://kergoth.com/

« 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.

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
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS