Concatenate variable names with numbers in Lua

Asked

Viewed 252 times

1

I have a problem, I need to do the following:

I have a variable that stores a number (x=3 for example)

And I have a chart like this:

tabela={}
tabela.var1='teste1'
tabela.var2='teste2'
tabela.var2='teste3'
tabela.var2='teste4'

I need to access this table by joining tabela.var with the variable x (in case 3), it would look like this

print(tabela.var..x)

But the value of tabela.var is nil. Have some way to make only after concatenation the program read as a variable?

  • 1

    In most similar cases it is better to do var be a subtable you can access with tabela.var[1], tabela.var[2], tabela.var[3], etc..

1 answer

0


The expression

tabela.var1

is equivalent to

tabela["var1"]

So try

print(tabela["var"..x])

However, consider this other way:

tabela={}
tabela.var={}
tabela.var[1]='teste1'
tabela.var[2]='teste2'
tabela.var[2]='teste3'
tabela.var[2]='teste4'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.