lua-users home
lua-l archive

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


On Nov 17, 2007 10:28 PM, Mark Sibly <blitzman@blitzbasic.com> wrote:
> Hi,
>
> Lua newbie here...
>
> I've just got the hang of using __index to access variables declared in
> an 'outer' scope/table, but I can't work out how to modify them.
> Instead, a new 'inner' variable always gets created.
>
> Is there any way to do this?
>
> Ideally, if I've got code like...
>
> HitPoints=HitPoints-10
>
> ...and HitPoints exists in an 'outer' environment, the outer version
> should be modified. If there is no outer version, a new HitPoints
> should be created in the inner env. Currently, using __index allows the
> code to 'read' the outer HitPoints, but not write it.
>
> Sorry for the lack of sample code, but it's a c/lua hybrid thingy,
> where c code sets up a new inner env using fsetenv, chaining it to an
> outer env using __index. I have a feeling I'll be able to do a lot of
> the C stuff in Lua eventually once I get bit more pratice though!
>
> Bye,
> Mark
>

Hi Mark,

The __index metamethod is only invoked when you attempt to read the
value of a key from a table that does not exist in the table. A
separate metamethod, __newindex, is called when you attempt to write a
value. (If a value already exists in a table for a particular key,
neither __index nor __newindex will be invoked when you try to read or
write it.)

-Duncan