What's happening in your first example is that A.__index == nil
. When you created 'A' on your first line here:
A = { __index = A }
The right-hand side of the the assignment 'A' evaluates to nil
since it doesn't exist yet at this point. As a result, later on when you set the metatable here:
An_A = setmetatable({},A)
it really ends up doing something akin to this:
An_A = setmetatable({}, {__index = nil} )
To get it to work the way you want, you have to make sure __index
isn't nil
. For example, assign it after table construction:
A = {}
A.__index = A
function A:speak()
print("I'm an A")
end
An_A = setmetatable({},A)
An_A:speak() --> outputs I'm an A