howto use a variable as an index into a table

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Post Reply
BertB
Posts: 72
Joined: Tuesday 24 June 2014 19:02
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: struggling and stumbling. Amsterdam area
Contact:

howto use a variable as an index into a table

Post 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.
Set 1= RPI 3B, latest Beta, RFLink USB, RFLINK WIFI, Zwave
Set 2= RPI 2B, Latest Beta, OTGW (USB), SBFSpot (Bluetooth)
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

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

Post 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)]
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 1 guest