Luau Object Oriented Programming

A table in Lua is an object in more than one sense. Like objects, tables have a state. Like objects, tables have an identity (a selfness) that is independent of their values; specifically, two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object. Like objects, tables have a life cycle that is independent of who created them or where they were created.

Check this video: https://youtu.be/g1iKA3lSFms?si=hHTzdD-2AMAPjl_j

Objects have their own operations. Tables also can have operations:

    Account = {balance = 0}
    function Account.withdraw (v)
      Account.balance = Account.balance - v
    end

This definition creates a new function and stores it in field withdraw of the Account object. Then, we can call it as

    Account.withdraw(100.00)

This kind of function is almost what we call a method. However, the use of the global name Account inside the function is a bad programming practice. First, this function will work only for this particular object. Second, even for this particular object the function will work only as long as the object is stored in that particular global variable; if we change the name of this object, withdraw does not work any more:

    a = Account; Account = nil
    a.withdraw(100.00)   -- ERROR!

Such behavior violates the previous principle that objects have independent life cycles.

Leave a Reply

Your email address will not be published. Required fields are marked *