Last active
November 14, 2015 14:17
-
-
Save josefnpat/50273f6501b0ad403cc1 to your computer and use it in GitHub Desktop.
Class concept for lua 5.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- implementation | |
function class(i) | |
local c = {fields={},field_types={}} | |
assert(type(i)=="table","class expects a table input.") | |
for type_name,default_value in pairs(i) do | |
local t,n = nil,nil | |
string.gsub( | |
type_name, | |
"(%l*)(%l*)", | |
function(i) | |
if i ~= "" then | |
if t then | |
n = i | |
else | |
t = i | |
end | |
end | |
end | |
) | |
assert(t ~= nil and n ~= nil,"`"..type_name.."` is not valid.") | |
c.fields[n] = default_value | |
c.field_types[n] = t | |
end | |
local mt = { | |
__newindex = function(n,v) | |
print('newindex',n,v) | |
assert(c.fields[n], | |
"Field `"..n.."` does not exist in class") | |
assert(c.field_types[n] == type(v), | |
"Field `"..n.."` expects `"..c[index].."`, got `"..type(v).."`.") | |
c[n] = v | |
end, | |
__call = c.new | |
} | |
c.new = function(init) | |
local self = {} | |
for i,v in pairs(c.fields) do | |
print("init",i,v) | |
end | |
setmetatable(self,mt) | |
return self | |
end | |
setmetatable(c,{ | |
__call = c.new | |
}) | |
return c | |
end | |
-- sample usage | |
local barclass = class{} | |
local fooclass = class{ | |
-- inherit = barclass, | |
-- lua | |
number_dt = 0, | |
-- string_name = "morris", | |
-- boolean_crazy = true, | |
-- table_randomobject = {}, | |
-- function_update = function(self,dt) self.dt = self.dt + dt end, | |
-- userdata_drawable = {},--love.graphics.newImage("butts.png"), | |
-- thread_loader = coroutine.create(function() end), | |
--[[ | |
-- nice? | |
int_age = 12, | |
readonly_int_starthp = 100, | |
bag_children = nil, | |
readonly_any_wat = nil, | |
color_background = {255,255,255,255}, | |
-- love? (many other types missing!) | |
image_spritesheet = love.graphics.newImage("map.png"), | |
source_hit = love.audio.newSource("ouch.ogg"), | |
--]] | |
} | |
foo = fooclass() | |
foo.dt = "potato" | |
print(foo.dt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment