lua-users home
lua-l archive

Lua 5.2 custom array demo

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


It isn't particularly useful, but notice __len and __ipairs;
definitely an advance!
local array = {}
local rawset,rawget,ipairs = rawset,rawget,ipairs
in array do
 function __len(t)
 return #t.store
 end
 function __newindex(t,i,val)
 rawset(t.store,i,val)
 end
 function __index(t,i)
 return rawget(t.store,i)
 end
 function __ipairs(t)
 return ipairs(t.store)
 end
end
function new_array ()
 return setmetatable({store={}},array)
end
t = new_array()
t[1] = 10
t[2] = 20
print(#t)
for i,v in ipairs(t) do print(i, v) end
=>
2
1 10
2 20
Of course, any mock-tables have to survive being passed to the table
functions, which traditionally do not cope well ;)
(__ipairs/__pairs is not currently documented)
steve d.

AltStyle によって変換されたページ (->オリジナル) /