lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


After reading module v. dofile discussion I was curious how people
handle OO constructs as Lua modules.  I like having the module itself
act as the "class" or "prototype" and use it as a constructor for an
instance of that module or class.  For example, to support the syntax:


-----------------------------------------------
local myobject = require("myobject")
local obj = myobject()
-----------------------------------------------

I use the following technique in the module script

-----------------------------------------------
local C = {}
local M

local
function setconstructor(m)
	M = m
	setmetatable(M, C)
end

module('myobject', setconstructor)

function C:__call(init)
    local m = setmetatable({}, M)
    -- init object
    return m
end

function M:method()
  -- some method
end

-----------------------------------------------