lua-users home
lua-l archive

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


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