lua-users home
lua-l archive

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


It was thus said that the Great Lorenzo Donati once stated:
> 
> Sorry for expressing my thought so badly, but mine was a sort of 
> half-baked "philosophical" rambling on Lua design about userdata :-)
> 
> So any enlightment is welcome (I only played shortly with C API and 
> although I know C, I cannot really call myself a C programmer, thus it 
> may well be that I missed completely the point of userdata and why their 
> usefulness is limited to C side!)

  It's used to add support for other data types.  I have code that
implements network addresses as a "userdata" for Lua [1].  I can do things
like:

	addr = net.address("192.168.1.10",'http')
	print(addr.family)	-- prints 'ip'
	print(addr.addr)	-- prints '192.168.1.10'
	print(addr.port)	-- prints 80

But more importantly, allow me to do stuff like:

	addr2 = net.address("fe00::1",33)
	print(addr)	-- prints 'ip:192.168.1.10:80'
	print(#addr)	-- prints 4
	print(#addr2)	-- prints 16
	if addr == addr2 then print "They are the same" end
	-- won't print anything as they're not the same family [2],
	-- not the same address, nor the same port. [3]

  -spc (Think of it as a way of mapping a C structure into Lua)

[1]	Why not use Luasockets?  Because it only supports IPv4, and is a
	huge amount of code for what I need.

[2]	I support IP, IPv6 and Unix domains.  

[3]	For those wondering, it's a userdata with the following metatable
	fields set:

		__index
		__tostring
		__len
		__eq
		__lt
		__le