How to create a simple importable class in Lua?

Viewed 1891

I'd like to create MyClass class in Lua in a separate file myclass.lua which I can import and use later. It should be working the following way:

local MyClass = require 'myclass'
tab = {1,2,3}
m = MyClass(tab)

However, following the code in Lua docs I can't make it work and am getting errors attempt to call global 'MyClass' (a table value).

The code I have written so far for myclass.lua:

local MyClass = {}
MyClass.__index = MyClass

function MyClass.__init(tab)
    self.tab = tab or {}
    setmetatable({},MyClass)
    return self
end
return MyClass

There is a plethora of examples how to write classes in Lua but I don't think I understand the difference and as a result getting lost in the implementation details. Is there a more or less conventional way to do it?

2 Answers
Related