user2977150
user2977150

Reputation: 11

Defining a table and then trying to call it's values using a string variable

I am having a few issues with tables and calling some values from them. Here is what I mean:

cartable = {"Car1", "Car2"}

table = "cartable"

for i = 1, #table do
print(table[i])
end

This is a very simplified version of my issue, but that is basically it. How can I use a string (must be using a string) to set a variable as a table?

Upvotes: 1

Views: 42

Answers (1)

Yu Hao
Yu Hao

Reputation: 122363

If it's a global variable like in your example, you can use _G[table] to access the variable with the name of that string.

for i = 1, #(_G[table]) do
     print(_G[table][i])
end

Upvotes: 1

Related Questions