[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: string like arrays
- From: "Duncan Cross" <duncan.cross@...>
- Date: Tue, 15 Jan 2008 23:24:24 +0000
On Jan 15, 2008 11:15 PM, Marco Antonio Abreu
<falecomigo@marcoabreu.eti.br> wrote:
> Hi,
>
> there is some how, in Lua, to access string bytes like an array;
> something like what we can use in C or Pascal?
>
> examples:
>
> s = 'Lua race'
> print( a[5] ) --> prints "r"
string.sub(a,5,5) or a:sub(5,5) will get an individual character for
you. If you really want the array notation, you can manipulate the
string metatable, something like this (though it would probably be
better to do it through the C API if possible):
debug.setmetatable('', {
__index = function(s,i)
if tonumber(i) then
return s:sub(i,i)
else
return string[i]
end
end;
})
> It would be very desirable to be able to write too, like:
>
> s[5] = 'f'
> print( s ) --> prints "Lua face"
This, however, is not possible - strings are immutable values. You
would have to roll your own mutable string-wrapping object to get
this.
-Duncan