Lua - Dynamically generated look up table & values

Viewed 41

I’m trying to create a table that is dynamically populated with the on/off status of set of switches I have. The following is where I I’ve got stuck as it always returns nothing/nil? ..

-- retrieved http.request status of 4 binary switches 
local P61v = 1
local P62v = 0
local P63v = 1
local P64v = 0

— following table should allow us to look up the status of all associated light by their  plug names P61, P62, P63 etc.

local LookupTable = {
    P61 = P61v,
    P62 = P62v,
    P63 = P63v,
    P64 = P64v
}
local x = LookupTable[P62]
print(x)
2 Answers

In LookupTable[P62] the expression P62 is evaluated to nil, resulting in LookupTable[nil] which resolves to nil.

What you are looking for is either

LookupTable.P62
-- or --
LookupTable['P62']

which are equivalent ways of expressing the same thing.

I created a script that defines both values, and this is what I ended up with..

local PowerResponse = "P61=0,P62=1,P63=0,P64=0"
local P61, _, P61v, P62, _, P62v, P63, _, P63v, P64, _, P64v = PowerResponse:match("(%w*)(=)(%d),(%w*)(=)(%d),(%w*)(=)(%d),(%w*)(=)(%d)")
local PowerStatusTable = {
        P61 = P61v,
        P62 = P62v,
        P63 = P63v,
        P64 = P64v
        }
--local x = PowerStatusTable[P62]
for k, v in pairs(PowerStatusTable) do
    luup.variable_set("urn:upnp-net:serviceId:IPPower1", k, v,deviceID)
end
Related