Code snippets‎ > ‎Lua‎ > ‎

Package

To make a package with instances you can create a metatable and re-use that.

Consider the package nghk:
local nghk={}
nghk.__index = nghk


function nghk.print(self)
  print(self.i)
end

function nghk.new()
  local self = setmetatable({}, nghk)
  self.i=5
  return self
end

return nghk

This package (nghk.lua) can be called as follows:
package.loaded.nghk=nil

nghk=require "nghk"

n=nghk.new()
n2=nghk.new()

n.i=3
n:print()
n2:print()

Comments