lua-users home
lua-l archive

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


 > 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"
 > 
 > It would be very desirable to be able to write too, like:
 > 
 > s[5] = 'f'
 > print( s ) --> prints "Lua face"
 > 
 > Thanks,

As an earlier poster pointed out, the first is easy with metatables,
and the second is impossible because Lua strings are immutable.

The other day I had to write a fast lexical analyzer in C, and I
wanted to write it in Lua first so I could debug it :-) I've taken out
all the zero-indexing bits, so the code below should do more or less
what you want.


--------------------------------------------------------------------------
local m = getmetatable('s')
if m and m.__index and type(m.__index) == 'table' then
  local t = m.__index
  m.__index = function(s, k)
                if type(k) == 'number' then
                  if k == s:len()+1 then
                    return '\0'
                  else
                    return s:sub(k, k)
                  end
                else
                  return t[k]
                end
              end
end