lua-users home
lua-l archive

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


David Given wrote:

On Thursday 13 October 2005 13:04, Jose Marin wrote:

Thinking on a more esay to use than a fast solution,
how hard would be to create a "String" class in Lua,
with the operator [] overloaded?


With Lua 5.1, I believe that the 'string' table is the default metatable for strings. So:

function string:__index(s, i)
  if (type(i) == "number") then
    return string.substr(s, i, i)
  end
  return nil
end

...might do what you want. (Untested. Never used Lua 5.1.)


This would work fine for ASCII, and maybe even for Latin1 in some cases. But if your string is UTF8, then you will possibly be getting intermediate bytes. Plus the count would be a byte count so if you want the nth character and there are UTF8 sequences before it, you will get the wrong character.

My Fusion package will have a Javascript String object which will make strings look like Unicode sequences and will support character indexing as well as things like split, join and substring.

--
chris marrin              ,""$, "As a general rule,don't solve puzzles
chris@marrin.com        b`    $  that open portals to Hell" ,,.
        ,.`           ,b`    ,`                            , 1$'
     ,|`             mP    ,`                              :$$'     ,mm
   ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
  m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
 b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
 ```"```'"    `"`         `""`        ""`                          ,P`