Lua Function Overloading

This script will allow you to overload functions based on the type of the parameters passed in. For example, the following

function asdf()
	print("A")
end

function asdf_number(x)
	print(x)
end

function asdf_number_number(x, y)
	print(y)
end

asdf()
asdf(3)
asdf(3,4)
asdf(4,5,3)

Actual Source code:

function string.split(t, b)
	local cmd = {}
	local match = "[^%s]+"
	if b then
		match = "%w+"
	end
	if type(b) == "string" then match = "[^"..b.."]+" end
	for word in string.gmatch(t, match) do
		table.insert(cmd, word)
	end
	return cmd
end

local __types = {number=1, string=2, table=3, boolean=4, ["function"]=5, ["nil"]=6}

local _mt = getmetatable(_G) or {}
_mt.__newindex = function(self, key, val)
	if type(val) ~= "function" then
		return rawset(self, key, val)
	end

	if not self.__registry then self.__registry = {} end

	local keys = key:split("_")
	local fn = keys[1]
	local types = keys
	table.remove(types, 1)
	for _i, type in ipairs(types) do
		if not type then
			self.__registry[fn] = {[0]=val}
			return rawset(self, key, val)
		end
		if not __types[type] then
			return rawset(self, key, val)
		end
	end

	local o_fn = rawget(self, fn) or function(...) return arg end
	local n_fn = function(...)
		local args = {...}
		for i, _type in ipairs(types) do
			if type(args[i]) ~= _type then
				return o_fn(...)
			end
		end
		return val(...)
	end
	return rawset(self, fn, n_fn)
end
_G=setmetatable(_G, _mt)
This entry was posted in Blog. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>