Walt Howard
Walt Howard

Reputation: 8208

Lua: how do I return the module itself when requiring a module?

I want to create a module something like this

myclass.lua

local myclass = {
  print = function()
`    print(myclass.name)
  end,
  setname = function(name)
    myclass.name = name
  end
}

-- Constructor
local function new(name)
  local o = {name = ""}
  setmetatable(o, myclass)
  return o
end

return _this_module__  <<== How can I do this?:

In order to use this module like this:

myclasscode = require("myclass")

local object1 = myclasscode.new("hello")
local object2 = myclasscode.new("goodbye")

Upvotes: 2

Views: 775

Answers (1)

Aki
Aki

Reputation: 2938

You need to define it on your own. The "module" here, or rather the thing that require returns is whatever is returned by the required file. For instance:

one.lua:

return 1

and then:

print(require("one")) --> 1

In the usual case you want to provide a set of functions to the user. Using tables is the most straight-forward choice to do it:

myclass.lua:

local function new(name)
  -- constructor code here
end

return {
  new=new,
  -- anything else that the module should provide
}

require will return the table with the 'new' member that holds the constructor function. User then can use it like this:

local myclass = require("myclass")
local instance = myclass.new("hey")

Because it's just a regular value you can do whatever you want with it. You can get quite close to what you wanted with:

local _this_module_ = {}

function _this_module_.new(name)
  -- constructor code here
end

return _this_module_

Upvotes: 3

Related Questions