lua-users home
lua-l archive

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


Steve,

If you like, it's easy enough to modify Lua to allow a getn tag
method. Here's a Lua implementation:

    _getn = getn  -- Save old getn function
    getn = function(obj)
        local mt = metatable(obj)
        if mt~=nil then
            local f=mt.getn
            if f~=nil then
                return f(obj)
            end
        end
        return _getn(obj)
    end

(Note that the above can be made shorter by using the "or" idiom.)

Now you can use it just like there was a built-in "getn" tag:

    MyMetaTable = {}
    MyMetaTable.get = function(obj) return 1 end -- always n=1

    t = {}
    print(getn(t))   -- prints 0
    metatable(t,MyMetaTable)
    print(getn(t))   -- prints 1

Note that this works fine with userdata too, since the modified
getn function does not check to make sure its argument is a 
table.

A C implementation would be faster of course.

Hope that helps.

  - Tom Wrensch

On Fri, 15 Feb 2002, Steve Dekorte wrote:

> 
> On Friday, February 15, 2002, at 07:34  AM, RLake@oxfam.org.uk wrote:
> > Ooooh, this is so *almost* what I want. Can't we please, please have a 
> > next
> > tagmethod to go with it? It would be soooo simple... (Yes, I know I can
> > write for k, v in metatable(object).next do ..., but that means that I 
> > need
> > to either write that always or know whether or not object is a regular
> > table; that is not good for code maintainability.)
> 
> A getn() tagmethod would be really nice too. Basically, it would be nice 
> to have userdata capable of replacing any value in Lua(particularly a 
> table value). This way userdata for a  database (like tdbm) can replace 
> a table or a userdata that handles arbitrary length numbers could 
> replace a number, etc.
> 
> Steve
> 
> 
>