lua-users home
lua-l archive

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


Hello all,

I wasn't acquainted with OOP strategies in Lua. What I know is that we
have nice options like Classlib, Loop, LOS... and the raw handling of
metatables.

Supppose the following structure:

-- [[
class number
method GetValue
property value
]] --

Now suppose the following function:

function number:GetValue()
return math.random(100)
end

I would like to do something like that:

number = number()
print(number.value)

The reply could be 80, 35, 44 or any randomic value between 0 and 100.

Using Classlib, LOOP or any other Lua library with OOP support, how
can I do this?

Could I directly handle the metatables? Certainly, I could do it, but
regarding my very few experience with metatables, I would prefer to
use a module with native property support. But is there this module?

Luciano


---------- Forwarded message ----------
From: luciano de souza <luchyanus@gmail.com>
Date: Wed, 27 Jun 2012 03:03:44 -0300
Subject: Defining a property with classlib
To: Lua mailing list <lua-l@lists.lua.org>

Hello all,

I am trying to implement a property with classlib, but the code does not work:

require('classlib')

class.number()

function number:__init()
local mt = getmetatable(self)

function mt.__index(t, k)
if k == 'value' then
return math.random(1000)
end
end
end

number = number()
print(number.value)

In stead of showing a ramdomic number, classlib raises an error.

This code works:

setmetatable(_G, {__index = function (t, k) return math.random(1000) end})

I would like to to the same but in the class scope. For this reason, I
tried also:

require('classlib')

class.number()

function number:__init()
local mt = getmetatable(self)

function mt.__index(t, k)
if k == 'value' then
return math.random(1000)
end
end
setmetatable(self, mt)
end

number = number()
print(number.value)

How to define a property using classlib?

Luciano