Saturday, July 30, 2016

Inheritance in Lua

Consider this code:

This is the output when run:

kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$ ./inheritance.lua
Calling constructor for table: 0x2414180
Accessing key = new for table: 0x2412f40; self = table: 0x2414180
Calling constructor for table: 0x2412f40
Accessing key = deposit for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = deposit for table: 0x2412f40; self = table: 0x2414180
Account:deposit(): self = table: 0x2411eb0
Accessing key = balance for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = balance for table: 0x2412f40; self = table: 0x2414180
Accessing key = withdraw for table: 0x2411eb0; self = table: 0x2412f40
SpecialAccount:withdraw(): self = table: 0x2411eb0
Accessing key = getLimit for table: 0x2411eb0; self = table: 0x2412f40
SpecialAccount:getLimit(): self = table: 0x2411eb0
Accessing key = get_balance for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = get_balance for table: 0x2412f40; self = table: 0x2414180
Account:get_balance(): self = table: 0x2411eb0
-100
kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$

Notice how searching for a key is recursive. When a key is not found in s, it is searched in SpecialAccount. When the key is not found in SpecialAccount, it is searched in Account.

No comments:

Post a Comment