[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Accessing String contents
- From: Michal Kottman <k0mpjut0r@...>
- Date: Thu, 21 Jun 2012 09:15:33 +0200
On 21 June 2012 05:49, Geoff Leyland <geoff_leyland@fastmail.fm> 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 Lua.org, 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
work:
getmetatable("").__index = function(s, i)
if type(i) == "number" then
return string.sub(s, i, i)
else
return string[i]
end
end
print(("hello world"):sub(7)[3]) --> r