lua-users home
lua-l archive

Re: Scripting language takes a silicon turn

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


David Given ha scritto:
FWIW, Raffaele Salmaso wrote a very neat object system based on closures where you used . to invoke methods. Pluses: the syntax change; instance data in methods was stored as upvalues, not table entries, making them an order of magnitude faster to access. Minuses: constructing objects was far more expensive, as you had to construct new closures for all the methods to bind the self parameter in.
here is the class function
---8<---
function class(super)
 -- create a new class description
 local klass = {}
 -- set the superclass (for object inheritance)
 setmetatable(klass, {
 __index = super,
 __call = function(self, ...)
 local tmp = {}
 setmetatable(tmp, klass)
 if self.init do
 self.init(tmp, unpack(arg))
 end
 return tmp
 end
 })
 klass.__index = function(table, key)
 local r = klass[key]
 if type(r) == 'function' do
 local f = function(...) return r(table, unpack(arg)) end
 table[key] = f
 return f
 else
 return r
 end
 end
 return klass
end
--->8---
with this function you can create classes and use the dot notation for calling methods.
stupid and useless class:
Animal = class()
function Animal.init(self, name)
	print(name)
	self.name = name
end
function Animal.canSitDown(self)
	return 'yes'
end
local a = Animal('otto')
print(a.canSitDown()) --> 'yes'
--
()_() | NN KAPISCO XK' CELLHAVETE T'ANNTO CN ME SL | +----
(o.o) | XK' SKRIVO 1 P'HO VELLOCE MA HALL'ORA DITTELO | +---+
'm m' | KE SIETE VOI K CI HAVVETE PROBBLEMI NO PENSATECI | O |
(___) | HE SENZA RANKORI CIAOOOO |
 raffaele punto salmaso at gmail punto com

AltStyle によって変換されたページ (->オリジナル) /