Forum

> > CS2D > General > Lua function subscriptions
Forums overviewCS2D overviewGeneral overviewLog in to reply

English Lua function subscriptions

1 reply
To the start Previous 1 Next To the start

old Lua function subscriptions

Lee
Moderator Off Offline

Quote
This is when you just need a quick fix to some function while you're programming and you don't want to go all the way through your code to find the original function. Or, when you have some type of event you want to trigger whenever something happens, here's how you do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
subscriptions = {}

function subscribe(fn_i, fn)
	if type(fn_i) == "string" then
		if type(_G[fn_i]) == "function" and type(fn) == "function" then
			local _fn = _G[fn_i]
			_G[fn_i] = function(args)
								local _r = fn(args)
								if _r then return _r end --Cancels the default behavior
								return _fn(args)
							end
			if not subscriptions [fn_i] then subscriptions [fn_i] = {} end
			subscriptions [fn_i][fn] = _fn
			local key = math.random(100000)
			while subscriptions [fn_i][key] do
				key = math.random(100000)
			end
			subscriptions [fn_i][key] = _fn
			return key
		else
			return nil
		end
	else
		return nil
	end
end

function unsubscribe(ifn, fn)
	if not subscriptions [ifn] then return false end
	if not (subscriptions [ifn][fn]) then return false end
	_G[ifn] = subscriptions [ifn][fn]
end

So for example, if you want to make the print() function print "Nothing to print" whenever you just call print() without any parameters, you just have to do this.

1
2
3
4
5
6
7
8
9
10
11
print("--Subscribing to the event--")
key = subscribe("print", function(str) if not str then print("Nothing to Print"); return true end end)

print()
print("Some stuff to print")

print("--Unsubscribing to the event--")
unsubscribe("print",key)

print()
print("Some stuff to print")

Output has written
--Subscribing to the event--
Nothing to Print
Some stuff to print
--Unsubscribing to the event--

Some stuff to print

old Re: Lua function subscriptions

Zune5
COMMUNITY BANNED Off Offline

Quote
This new Lua programming things is starting to get big

Admin/mod comment

and you are starting to be annoying by writing pointless spam. /DC
To the start Previous 1 Next To the start
Log in to replyGeneral overviewCS2D overviewForums overview