howto use a variable as an index into a table

Easy to use, 100% Lua-based event scripting framework.
Post Reply
BertB
Posts: 221
Joined: Tuesday 24 June 2014 19:02
Target OS: Raspberry Pi
Domoticz version:
Location: struggling and stumbling. Amsterdam area
Contact:

howto use a variable as an index into a table

Post by BertB » Sunday 12 August 2018 19:19

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.

User avatar
waaren
Posts: 1061
Joined: Tuesday 03 January 2017 15:18
Target OS: Raspberry Pi
Domoticz version: Beta
Location: Netherlands
Contact:

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

Post by waaren » Sunday 12 August 2018 22:01

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)]
Raspberry (debian stretch via berryboot on Synology DS916+) , Domoticz (almost) latest Beta, , dzVents 2.6, RFLink, RFXtrx433e, P1, Youless, Harmony, Hue, Yeelight, Xiaomi, HomeWizard, Zwave, Amazon echo

Post Reply

Who is online

Users browsing this forum: Jumper3126, McJohn and 0 guests