lua-users home
lua-l archive

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


You need to distinguish between variables and names. Variables are there own thing, they do not have names. Strings are their own thing, they do not have names. Variables can point to tables or to strings. Having a table with entries where keys are strings and values are other tables, is like having named entries. Global variables that are tables, with various names, are actually entries like this in the _G table.

Sent from my new BlackBerry Z10

From: iain morland
Sent: Friday, March 29, 2013 11:44 AM
To: lua-l@lists.lua.org
Reply To: Lua mailing list
Subject: RE: Convert string to variable name?

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