lua-users home
lua-l archive

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


Reuben Thomas escribió:


> I've just run into a problem with the fact that settag can only be used
> with tags created with newtag: if I want some operations on tables to
copy
> any table tag that is present, I must first check that it is not equal to
> tag({}).

This is one of the many reasons I have proposed an iterator tag method for
Lua.
It's hard to read between the lines to figure out what you're actually
trying
to do, but I am guessing that you wanted to do something like:

newtable = {}
for k, v in table do
  newtable[k] = v
end

but you can't because the iteration doesn't work on your table-objects. (At
least,
that is a problem I run into occasionally.)

With extended for and next, this works just fine. Of course, it doesn't
give you
a copy of the table; rather it gives you a vanilla table with the "same"
key-value
pairs. If may be that you want to define copy on all table types. The way I
generally do things like that is to define functions which are actually
table
lookups by tag, which allows you to define the functions on any Lua
datatype,
not just tables. Then you can say:

  newtable = Copy(table)

knowing that Copy for vanilla tables is defined as a foreach.

Even with "extended for and next", you can pull this off by defining
Foreach
in a similar way to Copy.

I'm putting together a little library with stuff like this in it, as a
sort of tutorial on tag-methods. If you're interested, I could e-mail
you a draft.

> Also, it's conceivable I might want to "untag" a table, which would be
> possible if I could say settag(t, tag({})).

I've run into that one, too. It can be kind of a pain. However, the Copy
idiom
shown above provides a work-around. In the general case, speaking as a
library
writer, I wouldn't want to expose my objects to being unsettaged. I know
what
you're thinking: the user could just use rawset/rawget. Not so!:

do
  local sysrawget = rawget

  function rawget(t, k)
    if it_is_my_table(t) then return t[k]
                         else return %sysrawget(t, k)
  end
end

> Another suggestion: stop settag returning a value. Functions that return
> the value of one of their arguments is a C-ism, like assignments
returning
> the value of the assigned quantity. It's a way to write nasty code.

I disagree. I use this all the time:

  self = {}
  -- set up keys
  return settag(self, %mytag)

R.