lua-users home
lua-l archive

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


On Sat, Sep 25, 2010 at 8:46 AM, Patrick Mc(avery
<spell_gooder_now@spellingbeewinnars.org> wrote:
> Would this scheme of prototypical inheritance be suitable for teaching
> someone who knew nothing about this topic?
>
> Surely the meta table approach is better but this code seems pretty easy,
> perhaps easier for someone new to programming.
   For what you're trying to demonstrate, don't you mean to set i=1
when you set r=toSort[i]? Instead of checking a chain of prototypes,
you're starting one step further into the chain each time.
   Second, it would probably help to have an inheritance example, with
e.g. selfDefense looked up for both cat and tabbyCat (or dog etc.), so
they can see that they share some stuff and individually override
others. Then you'd need a different lookup chain for each, though.

   With prototypes, I'd try to show how individual instances can have
their own custom behavior rather than needing a class per se. (I'm
assuming your grandma or whomever has a passing familiarity with
conventional single-dispatch class-based OOP.) Maybe something like
this?

[====[
-- just give this a meaningful name and tell them they can figure it out later
local function inherit(x, y) setmetatable(x, {__index=y}) end

mammal = {}
mammal.blood = function() return "warm" end
mammal.selfDefense = function() error("override me") end

cat = {}
inherit(cat, mammal)
cat.selfDefense = function() return "claws" end

dog = {}
inherit(dog, mammal)
dog.selfDefense = function() return "bite" end

-- this specific cat is secretly also a ninja
ninjaCat = {}
inherit(ninjaCat, cat)
ninjaCat.selfDefense = function() return "shuriken" end

print("cat -> ", cat.selfDefense())
print("dog -> ", dog.selfDefense())
print("ninjaCat -> ", ninjaCat.selfDefense())
]====]
cat -> claws
dog -> bite
ninjaCat -> shuriken

Thoughts?

Scott