Creación de objetos (que son simplemente las Tablas) es bastante diferente con Lua. La idea básica es crear una tabla regular que contenga atributos (funciones y valores) que sean comunes a todas las instancias. En esta tabla, llamaré CAT para la tabla de atributos comunes.
Si hace referencia a un atributo en una mesa y Lua no puede encontrar este atributo, hay una manera de contar Lua otro lugar para buscar el atributo. Queremos que Lua busque en el CAT los atributos comunes. Los metatablas responden a esa necesidad. Más sobre cómo funciona eso más tarde.
También necesitamos métodos en el CAT para poder usar valores de instancia. Self responde que necesita. Cuando llama a una función de tabla (método) de esta manera: tableName:methodName()
, Lua automáticamente coloca una referencia al objeto de tabla como el primer parámetro. El nombre de este parámetro es self. Aunque el método se encuentra en el CAT, self se referirá a la tabla de instancia de objeto de llamada particular.
Digamos que tenemos un CAT llamado Car.
metaCar = { __index = Car }
-- this table will be used as the metatable for all instances of Car
-- Lua will look in Car for attributes it can't find in the instance
Por ejemplo:
-- instance table is called mustang
-- setmetatable(mustang, metaCar)
Aquí es una función de propósito general que crea nuevos objetos instancia y establece el metatabla por ello. Si el CAT tiene una función de constructor (init), se ejecuta también.
function newObj(metatable)
..obj = {} -- create new empty instance object
..setmetatable(obj, metatable) –- connect the metatable to it
..if obj.init then -- if the CAT has an init method, execute it
....obj:init()
..end
..return obj
end
Encontré este "tutorial" en Lua [inheritance] (http: // lua-users.org/wiki/InheritanceTutorial) particularmente esclarecedor junto con esta respuesta. – Indolering
@Indolering Gracias. Puse tu enlace en la respuesta. –