Dynamic Variable, how to call it?

Guys,

How can i call a variable like this example:

[lua]local bg1 = “anything”
bg1.myName = “test1”
local bg2 = “something”
bg2.myName = “test2”

for i = 1,2 do
–The problem starts here. How can i call the variable dynamically?
print(bg[i].myName)
end[/lua]

In my case, i tryed to create it all in a table, but my game performance was terrible. So, i started to use my code not using tables ,like the example above, and my performance was perfect. But now i have to call some variables dynamically and i can’t find how.
I searched on the web how to do that on Lua and didn’t found anything.

Anyone can help me?
[import]uid: 127998 topic_id: 25343 reply_id: 325343[/import]

In lua, all global variables are in a global table named _G. You might be able to access them dynamically in that table if these are local to the global scope. I have not tested if this will work.

local bg1 = "anything"  
bg1.myName = "test1"  
local bg2 = "something"  
bg2.myName = "test2"  
   
for i = 1,2 do  
 local dynamic\_var = "bg" .. tostring(i)  
 print(\_G[dynamic\_var].myName)  
end  
  

[import]uid: 56820 topic_id: 25343 reply_id: 102332[/import]

You could use a table to store your variables and loops through it with pairs:

[code]
bgs = {}

bgs[“anything”] = { myName=“test1” }
bgs[“something”] = { myName=“test2” }

for k,v in pairs(bgs) do
print ( k, v.myName )
end

[/code] [import]uid: 44101 topic_id: 25343 reply_id: 102336[/import]

Table access is slower than a single variable, sure. But it shouldn’t cripple performance…

If you were doing a lot of table loops you can speed access to them up by doing something like:

  
for i = 1, #vars do  
 local myVar = vars[i]  
end  

Also note, that using

for 1 = 1, #whatever do

is faster than

for k, v in pairs do

and faster than

for k, v in ipairs do

Can you explain more about what you were doing with tables? [import]uid: 84637 topic_id: 25343 reply_id: 102734[/import]