lua-users home
lua-l archive

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


> ------------------------------
> Date: Mon, 20 Dec 2010 14:03:58 -0700
> From: HyperHacker <hyperhacker@gmail.com>
> Subject: Re: String indexing again
> To: Lua mailing list <lua-l@lists.lua.org>
> Message-ID:
> 	<AANLkTi=voiYapisjqz6gvb-c1oXMjgTe=Ma-Apb48MJ4@mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
> 
> On Mon, Dec 20, 2010 at 11:21,  <jgiors@threeeyessoftware.com> wrote:

<...snip...>

> > I think an argument against indexing of characters in a string is that
> > it implies indexing is acceptable on the left-hand side of an
> > assignment:
> >
> > s = "ABxDEF"
> > s[3] = "C"    -- Oh-oh...
> >
> > If I am not mistaken, this cannot work in standard Lua (i.e. there is no
> > way to make s contain "ABCDEF" after the assignment). The failure of
> > assigning to a character in a string would probably be just as confusing
> > as what you've mentioned above, especially if reading a character from a
> > string (with an array index) is allowed.
> >
> > John Giors
> > Independent Programmer
> > Three Eyes Software
> > jgiors@ThreeEyesSoftware.com
> > http://ThreeEyesSoftware.com
> 
> That could be done with __newindex. It might also allow s[3] = 65
> (assigning by character value instead of string).
>
<...snip...>

__newindex will not work since it does not have access to named variable
"s" [in my example]. It only receives a pass-by-value copy of the
string, and (as Drake Wilson replied) strings are immutable.

The best way to see the problem is to try to write a __newindex which
changes "s". Here is a Lua command-line example which demonstrates the
issue [note: it is not a full-blown assignment handler]:

Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
> m=getmetatable""
> m.__newindex=function(str,i,c)
>> print("string __newindex",str,i,c)
>> str="ABCDEF"
>> end
> s="ABxDEF"
> s[3]="C"
string __newindex       ABxDEF  3       C
> print(s)
ABxDEF


John Giors
Independent Programmer
Three Eyes Software
jgiors@ThreeEyesSoftware.com
http://ThreeEyesSoftware.com