lua-users home
lua-l archive

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


On Thu, Jun 28, 2012 at 8:59 AM, Cosmin Apreutesei
<cosmin.apreutesei@gmail.com> wrote:
>> Using Classlib, LOOP or any other Lua library with OOP support, how
>> can I do this?
>
> I did this as part of the winapi binding I'm working on. What you're
> looking for is in vobject.lua. It supports r/w and r/o properties and
> "stored" properties (those that have a setter but no getter). At a
> first glance I can't see any dependencies so you should be able to use
> the code without tweaking apart from the module organization.
>
> http://code.google.com/p/lua-winapi/source/browse/winapi/class.lua
> http://code.google.com/p/lua-winapi/source/browse/winapi/object.lua
> http://code.google.com/p/lua-winapi/source/browse/winapi/vobject.lua
>
> Hope it helps.
>

For what it is worth, there are a million ways to do classes and
learning them will be far more helpful than using a class library. My
advice is to use a class library once you understand how to do what
you need to do by using closures or metatables and are too busy or
lazy to do it yourself. By avoiding these baked-in methods, you'll
struggle to understand why something doesn't work or how to extend it
to do more than some library does on its own. Here's a simple example
of what you want (although mine makes a new result every time it is
called):

local function num(args)
	local private = args and args.private or {}
	local function GetValue() return math.random(100) end
	return setmetatable({}, {
		__index = function(self, index)
				return index == "value" and GetValue() or  private[index]
		end,
		__newindex = function(self, index, value)
			--do nothing. can't set value directly.
		end
	})
	
end
local my_num = num{private = {stuff = "hidden", other = "can't touch"}}
print(my_num.value, my_num.value, my_num.stuff)
-->76	9	hidden
my_num.stuff = "change it"
print(my_num.value, my_num.value, my_num.stuff)
--> 67	34	hidden