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)
    else
      rawset(t, k, v)
    end
  end })
end

someArray.With.A.LongName = {}

phpify(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
print(someArray.With.A.LongName[2]
-- 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
tables).

My 2 cents :)