Skip to content

Instantly share code, notes, and snippets.

@gvx
Created July 26, 2014 19:34
Show Gist options
  • Save gvx/4192a4d44e517f38bdac to your computer and use it in GitHub Desktop.
Save gvx/4192a4d44e517f38bdac to your computer and use it in GitHub Desktop.
A simple, alternative class system for Lua
return function(name)
local class = require(name)
local classmt = getmetatable(class)
if getmetatable(class) == nil then
local props = {unpack(class)}
for i = #class, 1, -1 do
class[i] = nil
end
local classmt = {}
local instancemt = {__index = class}
function classmt:__call(...)
local instance = {}
for i, property in ipairs(props) do
local value = select(i, ...)
instance[property] = value
end
return setmetatable(instance, instancemt)
end
function instancemt:__tostring()
local parts = {name .. '('}
for i, property in ipairs(props) do
parts[#parts + 1] = tostring(self[property])
parts[#parts + 1] = ', '
end
if #props > 0 then
parts[#parts] = ')'
else
parts[#parts + 1] = ')'
end
return table.concat(parts)
end
setmetatable(class, classmt)
end
return class
end
local getclass = require 'classes'
local vector = getclass 'vector'
print(vector(2, 7))
local v1 = vector(1, 1)
v1:add(vector(-10, -6))
print(v1)
local vector = {'x', 'y'}
function vector:add(vec)
self.x = self.x + vec.x
self.y = self.y + vec.y
end
return vector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment