[LUA] Use _G["var"] or array?

Status
Not open for further replies.
Level 15
Joined
Aug 7, 2013
Messages
1,342
Hi,

What is better style/practice if I want to reference a collection of variables that have the same name/form, but only differ on a parameter, e.g.

var_1
var_2
var_3
...

Would I make an array instead?

var[0] = "1"
var[1] = "2"
var[2] = "3"

and then reference the array member?

for i=0, 2 do
print(var)

or

for i=0, 2 do
print(_G["var_" .. i])
 
With N arbitrary values, still need N lines if I'm filling an array or N variables.

But yes the array works much better for loops anyway, and I chose that.

Thank you.
 
Arrays should be used when some form of dynamic memory access is required. If you are only ever accessing memory statically the index argument just adds overhead which degrades performance. In C/C++ the compiler will likely treat constant array indices as a static address offset (like a struct) or even constant addresses (if the array itself is in statically allocated memory) so emphasis is on readability.

Sadly WC3 does not do this and instead it will evaluate your constant index argument and pass it as an array index every time you access the array adding considerable overhead over using a separate variable. This is an extremely bad programming practice that was unfortunately encouraged by several people years ago resulting in a lot of poorly written GUI spells in the spell section.

Using constant array indices as part of an initialization stage or specific access stage is perfectly acceptable. As long as an index can be target of at least one dynamic index access then any constant index accesses done to it is fine and use of an array is justified. If an array only has constant index accesses then there is no reason ever to use an array as separate variables provide identical functionality.
 
Fortunately this script only gets called once and only once, so the array access time won't matter (it's a LUA array anyway), as it just makes the custom objects.
 
Status
Not open for further replies.
Back
Top