lua-users home
lua-l archive

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

2009/11/12 spir <>:
> * Is there a standard way to iterate _only_ on keys / values of a table; or items of table used as a plain array? (have written iterators for that, but would prefere to use std way)

You can iterate on keys using the pairs iterator:
    local keys = pairs
    for k in keys(t) do print(key, t[k]) end

To iterate over values, you would have to hide some iteration
information in the closure returned by the iterator, which would then
be unique to an iteration. This is a level of complexity above what
pairs is doing (but it's still reasonnably doable). What is usually
done is to skip the first iterator variable by naming it _ :
    for _,v in pairs(t) do print("value:", v) end

> * Is there a standard way to test for membership (in keys, values, items)? (I use the iterators above, but ditto)

You can test t[k]~=nil to check that a non-nil value is associated to
key k in table t. To check for values you need to iterate over the
table (and you may get several keys associated to a given value).

> * Is there a standard way to copy (clone) lua objects --especially tables?

There is no single way to do that. What about subtables ? Should they
be referenced by the new table, or cloned too ? What about recursive
references (t={}, t.itself = t) ? What about non-clonable members
(full userdata) ? You need to answer all these questions before
writing a table dump function, and my answers are probably not the
same as yours.