How can I define this variable before arrays?

Viewed 75

I make a LUA script for my game with the Logitech Gaming Software but I struggle with one thing.

I just want to define the variable "var" BEFORE the arrays.

I have more than 50 arrays so I'm tired of scrolling down everytime I want to change this variable..

How can I do it ?

Here is a simplified version of my script.

It works :

array1 = { "TRUE", 5, 4, 5, 5 }
array2 = { "FALSE", 6, 3, 8, 5 }
array3 = { "FALSE", 3, 2, 5, 3 }

var = array1

OutputLogMessage(var[1])

It doesn't work :

var = array1

array1 = { "TRUE", 5, 4, 5, 5 }
array2 = { "FALSE", 6, 3, 8, 5 }
array3 = { "FALSE", 3, 2, 5, 3 }

OutputLogMessage(var[1])
2 Answers

It doesn't work the second way because array1 doesn't exist at the moment when you copy it into var variable.

If you want to keep the code as it is now, i.e. creating arbitrarily named variables later, but specify the desired link upfront, you'll have to resolve assignment after you've created all the arrays. It could go like this:

var = "array1"

array1 = {blah-blah1}
array2 = {blah-blah2}
array2 = {blah-blah3}

-- this is where the var will be replaced with actual value
var = _G[var]

You can nest your arrays into an other array.

var = 1

arrays = {
    { "TRUE", 5, 4, 5, 5 },    --array1
    { "FALSE", 6, 3, 8, 5 },   --array2
    { "FALSE", 3, 2, 5, 3 },   --array3
}

print(arrays[var][1]) -- do stuff with first item in arrays[1]

This can clean up the code a bit, it would also allow you to collapse the arrays definition, in an ide that has that feature, so you dont have to scroll through them.


Additionally if you need the key to be a string you can define arrays like this:

var = "array1" -- must have the quotes

arrays = {
    array1 = { "TRUE", 5, 4, 5, 5 },
    array2 = { "FALSE", 6, 3, 8, 5 },
    array3 = { "FALSE", 3, 2, 5, 3 },
}

print(arrays[var][1]) -- do stuff with first item in arrays[array1]

This method is going to produce a table as apposed to the other method with produces an array. There is a difference in efficiency in favor of the first method, which is something to keep in mind.

Related