Is it possible to add custom methods to types/classes?

186 Views Asked by At

Like asked in the title, lets say I want to add a custom method to the table type, lets say table:printContent(), is there any way in Lua to achieve this? I mean only, pure, Lua. In C#, for example, you can use extensions to do that:

using System;
namespace Main {
    public static class Extension {
        public static void printContent(this table mytable) {
            foreach(var content in mytable) {
                Console.WriteLine(content.ToString());
            }
        }
    }  
}

Now is the same possible, only in Lua?

The question I inspired me from (that question didn‘t tought me what I wanted to learn, and yes I want OOP, if I want to mod for example in Lua)

How do I add a method to the table type?

1

There are 1 best solutions below

3
On

Ok, thanks, so its a no for tables, but can it be a yes for classes? Custom classes that aren‘t created by me (if I want to mod for example, there are classes before, what if I want to modify these classes? I could use a wrapper, but are there any other ways?)

A class is always implemented using Lua tables.

Minimum example:

MyClass = {}
function MyClass:new(o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  return o
end

If you want to add a new method to MyClass simply implement it

function MyClass:MyNewMethod()
end

The same way can of course be used to overwrite existing methods.