[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Multifunctions
- From: Lord Delvin <timm.felden@...>
- Date: Thu, 18 Oct 2007 23:00:14 +0200
As I allways wanted this function, and found out, that it's really
simple to do and I got so many good ideas from this list, I want to
share my code for this:
You need a Class system or you have to slightly rewrite it, depends on
what taste of lua you like most:)
The purpose of this code is to allow different behavior on different
signatures for functions, as function overloading does it for most
static typed languages.
I needed this to do better bindings to my application, as I often dont
know if I will get a vector or 2 or 3 numbers.
Feel free to use or comment it.
Greatings
Timm Felden
---------------------
--multifunction uses the type() function to determine the type of an
argument
--the type __default is a reserved word, so dont use it
multifunction = Class("multifunction");
--construction of a new multifunction
--#1 the multifunction
--#2 the default function, which gets called if type does not match
any function
--#2n-1 signature of the function
--#2n the function
multifunction.new = function(this, default, ...)
this.argType = {};
--set the default function
this.argType.__default = default;
--register functions
local name = "";
for _,i in pairs({...}) do
if _ % 2 == 0 then
this.argType[name] = i;
else
name = i;
end
end
end
--call searches for matching function
multifunction.__call = function(this, ...)
--create a type string ...
local signature = "";
for _,i in pairs({...}) do
if _ == 1 then
signature = type(i);
else
signature = signature .. " " .. type(i);
end
end
if this.argType[signature] then
this.argType[signature](...);
else
--we could not find the signature, so call default
print("default on: " .. signature)
this.argType.__default(...);
end
end
--adds a signature and function
--usage: f + {"<type>", f1}
multifunction.__add = function(this, t)
this.argType[t[1]] = t[2]
return this;
end
--used to unregister a function by signature
multifunction.__sub = function(this, sig)
this.argType[sig] = nil;
return this;
end
print("multi function loaded")
--usage--
do
local vec = function(x, y)
print("v={"..tostring(x)..","..tostring(y).."}") end
local s = function(s) print("string is: " .. s) end
local d = function(any) print(tostring(any)) end
local n = function() print"void" end
local f = multifunction(d, "number number", vec, "string", s)
f(3,4)
f("hallo welt!")
f()
--you can not use nil here as first type, as you can not pass a single nil
f = f + {"", n}
f(nil)
f = f - ""
end