lua-users home
lua-l archive

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


Hi,

Jean-Claude Wippler wrote:
> 
> Let's take Edgar Toernig's note in http://froese.exit.de/sol/
> Diffs2Lua :
> 
>     Tags are completely gone.  Instead, each object
>     has an attached method table.
> 
>     [...]
> 
>     Advantages: 1) No special interface needed for tag methods.
>     2) Object data and its methods are seperated.  No need to
>     copy all methods into each object.  3) Every datatype has
>     methods.  They mustn't be emulated with set/gettable.
> 
> Wouldn't the following standard Lua code solve this?
> 
>   local vtable = {
>     _tag_ = newtag(),
>     times = function (self,i) return self.v * i end,
>     hello = function () return "hi!" end,
>   }
> 
>   settagmethod(vtable._tag_, "index",
>     function (x,i) return %vtable[i] end)
> 
>   t = {}
>   settag(t, vtable._tag_)
> 
>   t.v = 111
> 
>   assert(t.v == 111)
>   assert(t.none == nil)
>   assert(t:times(222) == 24642)
>   assert(t.hello() == "hi!")

Not at all.  '.' and ':' access _different_ tables (r/w).
And, you missed the first and third point ;-)  An examples:

	x = File.open("foo")
	x:write("Hello World!\n")

The x is a userdata.  Its method table is File and x:write ==
File.write, a normal function.  No magic involved.  You can
redirect/overload the write function, add your own high-level
functions, ...

	function File.printf(file, args[])
		file:write(format(args[]))
	end
	x:printf("%4x", 48879)

	function printf(args[])
		File.stdout:print(args[])
	end
	printf("The answer is '%d'!", 42)

And don't forget, it's less code, simpler handling and same
speed :-)

Ciao, ET.


PS: another one?  Let's make File callable.  Calling it will
open a file:

	methods(File, {})	# File gets its own methods
	function File:call(tbl, name, mode)	# and the call method
		return tbl.open(name, mode)
	end
	x = File("tmp", "w")