lua-users home
lua-l archive

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


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