lua-users home
lua-l archive

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

On Wed, Feb 26, 2014 at 2:12 PM, arioch82 <> wrote:
> how would i do that? how can i define a table to be "copied over" to the
> instance?
> Thanks again

Penlight works this way (not to keep sounding like a commercial for it. :)

when you set the index metamethod of your object to self, within new,
then you're saying that the class fields are the fall back to your
object. So, if the object has the field assigned, then it never checks
the class. You have the object table inside of the New constructor.

local class = require 'pl'.class

local My_class = class.My_class()

function My_class:method(args) --all objects will use *this* function
(not a just copy of it), if the program accesses the "method" field.
  --do method stuff
  self.objcect_prop = args.value ---etc


function My_class:_init(constructor_args) --- you called this "New".
It's init in Penlight = --only this object will have this.



In Pen light, the My_class.__call metamethod is a function that calls
this _init function, passing in a new object table as the first
argument. So it's something like this:

__call = function (klass, ...)

    local obj = {}
    --blablabla, features features features

   klass._init(obj, ...) --do the stuff init the init function
   setmetatable(obj, klass)

  return obj


It's a little more complicated, because penlight also supports
getters/setters and other fun.

When you do inheritance, you need to decide if you're going to flatten
the objects so that there is only one metatable. That is, the last
inherited Class filters any previous fields (properties or methods).
The other way is to tell your __index method to loop through an
inheritance chain.

Penlight flattens (i believe). This is faster, but there may be a
conceived behavior of OOP that does not work with this.

As Javier said: Lua doesn't have objects. But, you can fake them really well. :)

AND: this is one thing that took me a while to learn....

Start with very little "pop" behavior. Do you really really really
need all the features of some other language that you've used? Lua can
do a crazy amount with very little. Just some wounds from experience.