lua-users home
lua-l archive

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


allthough I am interested in Lua since ca. Lua 5.0 but I only recently have the opportunity to investigate it further. Right now, I try to grasp the OO-like programming style using Lua.

As Lua seems to be very flexible despite its few clean and concise concepts, I thought I may be able to use it like I am used to, while programming in other languages before. But there seem something slipping me right now ...

I have already searched in the mailing list archive, but found no answer that really convince me, that what I want is not possible in Lua.
So after this long introduction I come to my problem.

I try to implement a Range class, that will contains start, stop and step members to describe a range (list) of numbers without explicitely instanciating it. That means a range (1,9,2) would virtually describe the list [1, 3, 5, 7, 9[.

That already works. But now I would also allow for using of operator '#' to get the length of that range. My implementation currently is as follows:

  Range = {}
  setmetatable(Range, Range)
  Range.__index = Range
  function Range:new(b, e, s)
    return setmetatable({ start = b, stop = e, step = s or 1 }, self)
  function Range:__len()
    return math.floor((self.stop - self.start + 1) / self.step + 0.5)

I would like to use it like e.g. this:

  r1 = Range:new(1, 9, 2)
  print (#r1)  -- displaying 5 (but does not right now!)

But unfortunately I get only a '0' every time. But calling it like this:


or even this:


delivers the expected '5'. So I looked into the reference manual and it seems that my '__len' will never be called because type(Range) == "table".

Now my question is: how do I possibly achieve my desire? It ought to be possible IMO, as tables are Lua's way to build more complex datastructures if I did understand correctly. And then it could make sense to implement/overwrite the operator '#' (thinking for single pointered lists, for instance).

So what can I do? Thanks in advance for any hint.