lua-users home
lua-l archive

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


On Sat, Mar 30, 2013 at 2:45 AM, iain morland <iain@iainmorland.net> wrote:
> Thanks for the responses, both on- and off-list.
>
> Sean Conner wrote:
>> > So how could I get the string that's returned by MyTable[i] to be
>> > "seen" by Lua as a variable name?
>>
>>   Um ... _G[MyTable[i]].attribute?  So what exactly are you trying to do?
>
> This does indeed work, but I don't quite understand why.
>
> If I declare MyTable as a global variable in the main code chunk (executed
> when the script is initialised), then in a subsequent callback, I can do
> what Sean describes, as intended.
>
> I can get the same result if I declare MyTable as a local variable in the
> main code chunk.
>
> But if, having declared MyTable as local in the main code chunk, I then
> remove the _G[] from around _G[MyTable[i]].attribute=value, I get the error
> message that Lua is trying to index a string value.
>
> Yet, in the same scenario, I don't need the _G[] in my callback to do this:
>
> print(MyTable[i])
>
> So I'm a little confused. Why do I need _G[] even if MyTable is local - and
> why *don't* I need _G[] in order to print the contents of MyTable?
>
> Sorry for any clumsy expression of these queries. I am still learning (as if
> that weren't obvious!).
> TIA,
> Iain
>
>
>
>

The value referenced by MyTable[i] is a string. When you do
_G[MyTable[i]].attribute=value, that's equivalent to
_G["somestring"].attribute = value (assuming MyTable[i] is the string
"somestring"). That is, you're looking up the "somestring" field of
the _G table and then setting the "attribute" field of that to
`value`.

When you do MyTable[i].attribute=value (without the _G[]), that's
equivalent to "somestring".attribute=value. That is, you're trying to
set the "attribute" field of the string "somestring" to `value` (which
will normally throw an error, since you can't set fields of
strings[1]).

In the first case, you're using the string as a table key to look up
another table and set a field in that second table. In the second
case, you're just trying to set a field of a string (which doesn't
work, as I explained above).

print(MyTable[i]) is equivalent to print("somestring"), that is "print
this string to the standard output".

_G is the global environment[2], but it's just a table and behaves
like any other table.

Hopefully this should clear things up a bit.

[1] You could define a __newindex metamethod for strings, but it's
probably a bad idea in most cases, especially if your code will be
used by other people or their code.

[2] See the reference manual of your Lua version for a complete
explanation of _G and environments:
         http://www.lua.org/manual/5.1/manual.html#2.9
         http://www.lua.org/manual/5.2/manual.html#2.2