lua-users home
lua-l archive

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


On 16.12.2009 15:01, Hans Hagen wrote:
> steve donovan wrote:
>> On Wed, Dec 16, 2009 at 3:29 PM, Hans Hagen <pragma@wxs.nl> wrote:
>>> The following is valid lua
>>>
>>> a = "text"
>>> b = a[3]
>>
>> Yes, given that there is no index operator for strings it seems odd
>> that we don't get an error. The reason is that strings have a
>> metatable with __index pointing to the string table; looking up [3] on
>> s leads to string[3] which gives the nil as you've noticed.
>>
>> If you're prepared to modify the metatable of all strings, then you
>> can define a[3] in this case to be a:sub(3,3)
> 
> can you give an example? __index gets a (table, n) passed and not the
> string itself

Check this out:

s="qwerty"
MT=getmetatable(s)
MT.__index=function(obj,key)
  if type(key)=='number' then
    local char=obj:sub(key, key)
    assert(#char>0, "Illegal index: "..key.." for string "..obj)
    return char
  else
    return string[key]
  end
end

print(s[3]..s[2])
print(s[9])

Regards,
miko