Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make a string to a variable?

I'm making a table and I would like to make a variable from a string...

local STRING_NAME = "Test1"

local MyTable = {
STRING_NAME = "Hello World"
}

Well I know that I can write Test1 = "Hello World", but the problem is that I need to make the variable name from the string itself because I need to insert a table inside a table like that:

local FirstTable = {MyTable = {STRING_NAME = "Hello World"}, game.Workspace.Part}

Well, if anyone know how I can do this, thanks.

1 answer

✓ Accepted answer

There are two ways you can add an entry to a table with a variable index:

Define it when you create the table:

local MyTable = {[STRING_NAME]= "Hello World"}

Add it after the table is already created:

MyTable[STRING_NAME] = "Hello World!"

Enclosing something in square brackets will have the table compute whatever is inside those brackets before using it. That means you can also do something like this:

function test()
    return "a"
end
local MyTable = {[test()] = 3}

and if you print the table out, you'll see that MyTable has an entry named "a" with a value of 3.

This discussion is preserved as it was. New answers, comments, and votes are closed.