Page 1 of 1

howto use a variable as an index into a table

Posted: Sunday 12 August 2018 19:19
by BertB
Is it possible to use a variable as an index into a table?

Here I have a part of my code.
MyStateList=MyDevice.state it contains all attributes of a device.
MyDesc=MyDevice.description. In it I have a number (1) and a part of an URL string.

The number, MyCommands[1], is an index into the table MyStates.
I would like to get a MyValue=MyStates[MyIndex]

This does not work.

Code: Select all

                MyStates = {}
                for MyState in string.gmatch(MyStateList, "[^;]+") do
                    MyStates[#MyStates + 1] = MyState
                    print(#MyStates .. '-' .. MyState)
                end
            
                MyCommands = {}
                for MyCommand in string.gmatch(MyDesc, "[^|]+") do
                    MyCommands[#MyCommands + 1] = MyCommand
                    print(#MyCommands .. '-' .. MyCommand)
                end

                MyIndex=MyCommands[1]
                MyIPString=MyCommands[2]
                MyValue=MyStates[MyIndex] 
                print(MyIndex)  -- this gives 1
                print(MyIPString)   -- this gives part of the URL
                print(MyValue)  --  attempt to concatenate global 'MyValue' (a nil value)
           
When I do MyVlue=MyCommands[1] it works fine.

Re: howto use a variable as an index into a table

Posted: Sunday 12 August 2018 22:01
by waaren
BertB wrote: Sunday 12 August 2018 19:19 Is it possible to use a variable as an index into a table?

The number, MyCommands[1], is an index into the table MyStates.
I would like to get a MyValue=MyStates[MyIndex]

When I do MyVlue=MyCommands[1] it works fine.
Maybe you have more luck if you change

Code: Select all

MyValue=MyStates[MyIndex] 
to

Code: Select all

MyValue=MyStates[tonumber(MyIndex)]