2

I just answered a Python question which "required" inheriting a class from int (immutable type in Python). I've been doing some Lua lately and as I answered the question, I thought; "How is this done in Lua?"

So, can I inherit a class from an immutable type in Lua? If yes, how? And if inheriting from a class such as integer is not possible, is there an other way to implement behavior similar to the one in my answer on the Python question?

As a sidenote, I'm still having quite a lot of trouble understanding Lua's metatables.

Community
  • 1
  • 1

1 Answers1

1

First of all, Lua does not have an object oriented policy. From PiL2, chapter 15:

Usually, Lua does not set policies. Instead, Lua provides mechanisms that are powerful enough for groups of developers to implement the policies that best suit them.

There are many approaches to object oriented programming in Lua.

In Lua, int is not a class. It is not even a type (Lua uses C double to represent numbers by default).

That said, it is possible to use a metatable to make a table immutable. So, if you are using tables to implement your classes (or prototypes), then you can certainly inherit from them. You can also use userdata for your class or prototype, and its (im)mutability would be established by your C library that creates the userdata.

You can read about immutable tables in PiL 13.4.5. You should read chapters 13 and 16 to learn about metatables and OOP in Lua.

If you want further examples, the LOOP package implements several OOP models.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119