lua-users home
lua-l archive

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

A possible alternative in pure Lua is:

-- Lua starts here
function phpify(array)
  setmetatable(array, { __newindex = function(t, k, v)
    if k==-1 or k=="append" or k=="push" then
      table.insert(t, v)
      rawset(t, k, v)
  end })

someArray.With.A.LongName = {}


someArray.With.A.LongName[-1]       = "foo" -- append at the end
someArray.With.A.LongName["append"] = "bar" -- append at the end
someArray.With.A.LongName["push"]   = "baz" -- append at the end

someArray.With.A.LongName[2] = "foobar" -- replace element
-- Lua stops here

It only requires the -1 index to be free (-1 can be replaced with any
special value). For subsequent access (read AND write) of existing
elements it skips the metamethod lookup (newindex is not called if
element is already existing). A possible refinement is to check for
existing metatable.

Perf is not very good, but syntax is short. Above all it does not
require any Lua syntax modification (only some semantics of your

My 2 cents :)