[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: array indices in lua
- From: Mark Feldman <mfeldman@...>
- Date: Mon, 30 Nov 2009 12:33:07 +1100
cynthia powers wrote:
if I could have everything starting from 0, life would gets a lot
easier for me...
You can do it with metatables but the # length operator will no longer
work properly (overloading the _len operator doesn't work with regular
tables in the current version of Lua):
function zero_index(t)
local new_t = {__old_t=t}
setmetatable(new_t, new_t)
new_t.__index = function(self, key)
if tonumber(key) then return self.__old_t[key+1]
else return self.__old_t[key]
end
end
new_t.__newindex = function(self, key, value)
if tonumber(key) then self.__old_t[key+1] = value
else self.__old_t[key] = value
end
end
return new_t
end
t = {"a", "b", "c", foo="bar"}
print(t[1], t[2], t[3], t.foo) --> a b c bar
t = zero_index(t)
print(t[0], t[1], t[2], t.foo) --> a b c bar
Mark Feldman
This message and its attachments may contain legally privileged or confidential information. This message is intended for the use of the individual or entity to which it is addressed. If you are not the addressee indicated in this message, or the employee or agent responsible for delivering the message to the intended recipient, you may not copy or deliver this message or its attachments to anyone. Rather, you should permanently delete this message and its attachments and kindly notify the sender by reply e-mail. Any content of this message and its attachments, which does not relate to the official business of the sending company must be taken not to have been sent or endorsed by the sending company or any of its related entities. No warranty is made that the e-mail or attachment(s) are free from computer virus or other defect.