lua-users home
lua-l archive

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

On 21 June 2012 05:49, Geoff Leyland <> wrote:
> On 21/06/2012, at 3:43 PM, Coda Highland wrote:
>> Strings are tables, but the characters aren't table elements. Lua
>> doesn't offer that sugar.
> But you can always do it yourself:
> Lua 5.2.1  Copyright (C) 1994-2012, PUC-Rio
>> debug.setmetatable("", { __index=function(s, i) return string.sub(s, i, i) end })
>> =("hello")[5]
> o

This removes the ability to call string methods on the string itself,
like str:sub(...). You can change it as follows to make sure both ways

getmetatable("").__index = function(s, i)
  if type(i) == "number" then
    return string.sub(s, i, i)
    return string[i]

print(("hello world"):sub(7)[3]) --> r