lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi!

(sorry for lenghty post, but note 1. below is quite interesting regarding token filtering, skip the rest if you don't care for a class system)

I've begun a small attempt at a class system implemented with token filters.

Find it here: http://kaos.explosive.se/svn/lua/class.lua
This one requires the new token filter patch from lhf.

I have a few points of consideration regarding the use of the FILTER function:

1) When token <eof> is encountered, make sure you return (not yield) and restore the original FILTER so that you are ready for the next source to be parsed. To see what I mean, add -i when you run the fnext.lua filter over test.lua from the tokenf archive.
Demo:
kaos@jenna ~/prog/lua-5.1.1/tokenf $ ./a.out -lfnext -i test.lua
Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
A       1       100
A       2       200
A       3       300
B       1       100
B       2       200
B       3       300
> =123
> -- notice: no output!
>
> print("FOO")
>

2) Well, that was the main thing really

3) On to the class system. I'm so used to not use classes so I didn't really know what to put in there - and had the feeling that maybe it should be interacting more with the module system.. ? There is one quite silly cludge to solve inheritance, and that is a local __<class name>_key variable with a random number used during subclassing. Also: subclasses that join two branches of a common ancestor doesn't quite do what would be expected (only the first instance of each class will be used), so if that is needed, that issue needs to be resolved.

4) Example Account class, inspired by PIL:

class Account do
	function deposit( v )
		print("Account.deposit()", v)
		self.balance = self.balance + v
	end

	function withdraw( v )
		print("Account.withdraw()", v)
		if v > self.balance then error("Insufficient funds", 2) end
		self.balance = self.balance - v
	end

	function getBalance()
		print("Account.getBalance()", self.balance)
		return self.balance
	end

private
	balance = 0

endclass

class BonusAccount, Account do
	function getBalance()
		print("BonusAccount.getBalance()", self.balance * 1.2)
		return base.getBalance() * 1.2
	end

endclass

class SpecialBonusAccount, BonusAccount do
	function withdraw( v )
		print("SpecialAccount.withdraw()", v)
		if v - self.getBalance() >= self.getLimit() then
			error("Insufficient funds", 2)
		end
		base.balance = base.balance - v
	end

private
	limit = 1000.00

	function getLimit()
		print("SpecialAccount.getLimit()", self.limit)
		return self.limit
	end

endclass


Example use:

acc = SpecialBonusAccount()
acc.deposit(250)
print("acc balance: ", acc.getBalance())

For more details, see comments in class.lua

Any o(pi)nions?!


Regards,
Andreas