Last active
August 29, 2015 14:16
-
-
Save erinlin/440112d6ea4cce9deab3 to your computer and use it in GitHub Desktop.
[CoronaSDK/Lua] Function Delegate2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
------------------------------------- | |
-- function delegate part 2 | |
-- Author: Erin Lin | |
-- www.erinylin.com | |
-- 簡易模擬 C# delegate | |
-- licensed under the MIT license. | |
-- 2015, 03 | |
-- 參考:https://gist.github.com/anonymous/3f0e5b046bfdcfa9864a | |
------------------------------------- | |
local next = next | |
local unpack = unpack | |
local t = { | |
remove = table.remove, | |
insert = table.insert, | |
indexOf = function(list, value) | |
local n = 0 | |
for k, v in next, list do | |
if v==value then return k end | |
end | |
return -1 | |
end | |
} | |
local meta = { | |
__add = function(x, y) | |
if type(y) == "function" then | |
t.insert(x, y) | |
return x | |
elseif type(y) == "table" then | |
for i=1,#y do | |
if type(y[i]) == "function" then t.insert( x, y[i] ) end | |
end | |
return x | |
end | |
end, | |
__sub = function(x, y) | |
if type(y) == "function" then | |
local index = t.indexOf( x, y ) | |
if index > -1 then t.remove( x, index ) end | |
return x | |
elseif type(y) == "table" then | |
for i=#y,1,-1 do | |
local index = t.indexOf( x, y[i] ) | |
if index > -1 then t.remove( x, index ) end | |
end | |
return x | |
end | |
end, | |
__call = function(d, ...) | |
for i,v in next, d do | |
v(...) | |
end | |
end | |
} | |
local meta2 = { | |
__add = meta.__add, | |
__sub = meta.__sub, | |
__call = function( d, ... ) | |
local result = arg or {} | |
for i,v in next, d do | |
result = { v( unpack(result) ) } | |
end | |
return unpack(result) | |
end | |
} | |
local function newDelegate( bool ) | |
local d = {} | |
--bool==false, use same arguments for every function | |
--bool==true, will pass retrun result to next function | |
setmetatable(d, bool and meta2 or meta) | |
return d | |
end | |
------------------------------------- | |
-- | |
------------------------------------- | |
local function step1( n ) | |
print("Step1", n, n + 10 ) | |
return n + 10 | |
end | |
local function step2( n ) | |
print("Step2", n, n + 20 ) | |
return n + 20 | |
end | |
local function step3( n ) | |
print("Step3", n, n + 30 ) | |
return n + 30 | |
end | |
local d = newDelegate() | |
local d2 = newDelegate( true ) | |
d = d + { step3, step2 } | |
d2 = d2 + { step1, step2, step3 } | |
print("d(0):") | |
d( 0 ) | |
d = d - step2 | |
print("d = d - step2 ; d(0)") | |
d( 0 ) | |
print("d2( 100 ):") | |
d2( 100 ) | |
print("-----------------") | |
d2 = d2 - step2 | |
print("d2 = d2 - step2 ; d2(100)") | |
d2( 100 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment