lua-users home
lua-l archive

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


On Sat, Feb 23, 2013 at 10:46 AM, <mlepage@antimeta.com> wrote:
> That makes the metatable for the monster. (Roughly comparable to C++ class.)
>
> Then three lines to set the metatable itself as its __index, so those methods can be used.
>
> When a monster is created, it gets that metatable. That's how it can rawr.
>

Metatables extend the behavior of a type (usually tables or
uservalues) on some operations. If one defines the "__index" as a
table, all existing keys are looked on that table:

meta_t = {
  lol = 'meta_t lol',
  bla = 'meta_t bla',
}
meta_t.__index = meta_t

t1 = {bla = 't1 bla'}
setmetatable(t1, meta_t)
print(t1.lol) --> will print "meta_t lol"
print(t1.bla) --> will print "t1 bla"

In your example case, this is done so you can access Monster methods
from lua. So when in Lua you do 'monster1:rawr()', lua searches for
the 'rawr' field on the MetaMonster metatable. =)

I hope I wasn't too confusing. =P Anyway, you can read more about
metatables on the Reference Manual [1] [2] or on PIL [3].

[1] 5.1 -> http://www.lua.org/manual/5.1/manual.html#2.8
[2] 5.2 -> http://www.lua.org/manual/5.2/manual.html#2.4
[3] 5.0, but still largely relevant: http://www.lua.org/pil/13.html

--
NI!