lua-users home
lua-l archive

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


On 07/15/2011 02:05 PM, Dirk Laurie wrote:
In December 20 we had a discussion on string indexing and table slicing.
I've extracted what I liked about that discussion and put it on the Wiki.
     http://lua-users.org/wiki/StringIndexing

If you make j optional you could support indexing and slicing with the single call syntax:


getmetatable('').__call = function(str,i,j)
  if type(i)~='table' then return string.sub(str,i,j or i)
  else local t={}
    for k,v in ipairs(i) do t[k]=string.sub(str,v,v) end
    return table.concat(t)
  end
end

-- demo

a='abcdef'

print (a[4])       --> d
print (a(4))       --> d
print (a(3,5))     --> cde