lua-users home
lua-l archive

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


On Feb 20, 2008 4:14 AM, John Hind <john.hind@zen.co.uk> wrote:
> Reading Roberto's "Programming in Lua" 2nd Edition, I was struck by the
> inconsistency between the String library and the Table library - in Lua 5.1
> the former's functions can be used as methods on a String object while the
> latter can only be used as "traditional" library functions.

A string metatable doesn't pollute your string content. A table metatable does.

For instance, when you create a new table, you expect it to be empty:

   t = {}
   print(t.maxn) -- should be nil!
   print(t.sort) -- should be nil!
   ...

Having certain lookups (setn, insert, getn, foreachi, maxn, foreach,
concat, remove, sort) return non-nil values on a supposedly empty
table is going to break certain usages of a table.

If you want that behavior, you can always just use your own table constructor:

   function table.new(t)
      return setmetatable(t or {}, {__index=table})
   end

   t = table.new{ "One", "Two", "Three" }
   t:insert("Foo")
   t:insert("Bar")
   t:sort()

   for k,v in pairs(t) do print(k,v) end

Cheers,
Eric