Jump to content

User:OrenBochman/Lua Objects

From Meta, a Wikimedia project coordination wiki


Lue does not support object-oriented programming in the traditional sense. The C++ class, inheritance, operator overloading and polymorphism are missing. However it is possible to introduce some of these into Lua using meta-programming techniques similar to current practice in Javascirpt. This means that object-oriented development is possible in Lua but that additional overhead is required as well as documention of the technuqe used.

Introducing objects

[edit]
  • Objects are created using tables in a variety of syntaxes, similar to JavaScript.
  • Private member variables implemented using lexical scoping, as in JavaScript
  • Dot for static methods: obj.func()
  • Colon for non-static methods: obj:func()


Factory function style example

function newObj()
    local private = 1
    local obj = {}

    function obj:getPrivate()
        return private
    end

    return obj
end

Using metatables

[edit]
  • Each table may have an attached metatable
  • Provides operator overloading
  • "index" metatable entry is used for object inheritance and prototype-based OOP

Class Definition

[edit]
Account = {}
Account.__index = Account

function Account.create(balance)
     local acnt = {}             -- our new object
     setmetatable(acnt,Account)  -- make Account handle lookup
     acnt.balance = balance      -- initialize our object
     return acnt
end

function Account:withdraw(amount)
     self.balance = self.balance - amount
end

-- create and use an Account
acc = Account.create(1000)
acc:withdraw(100)

Object Creation

[edit]
  • we use an awkward yer usefull neted constructor.
  • using this setup an intilization function is provided and the constructor is automaticaly generated.


Account = class(function(acc,balance) acc.balance = balance end)

function Account:withdraw(amount)   
self.balance = self.balance - amount end 

-- can create an Account using call notation!
acc = Account(1000)
acc:withdraw(100)

Inheritence

[edit]

See Also

[edit]