Page 1 of 1

I still don't understand tables...

Posted: Saturday 19 February 2022 18:29
by Sarcas
I've spent hours reading at lua.org, lua-users.org and numerous other sites, looked at a lot of examples here at the forum, but somehow I still don't understand tables. Perhaps it has to do with the fact that I learned myself programming some 40+ years ago when i was a kid. BASIC and Pascal and dialects. I understand tables are not the arrays I used to know, but somehow I just can't grasp it.

I want to make a table ('myTable'). The index has to be a Domoticz device ID (DzDeviceID), the trigger. When that device triggers, I need to look up a premade api/json so I can open it (onActionUrl), and more info, like the name of the trigger (triggerName).

So, in my fantasy LaLaLua-language I need to do something like

Code: Select all

myTable[DzDeviceID].onActionUrl = myPremadeUrl
myTable[DzDeviceID].triggerName= thetriggername
etc
Obviously, it doesn't work.
I tried variations of declaring the array, like:

Code: Select all

local myTable= { 
            onActionUrl= {},
            triggerName= {}
        }
But I have really no clue what I am doing.

Do I need to use

Code: Select all

insert.table
? I tried to use tables as unordered sets, because the order is irrelevant. The example doesn't use the

Code: Select all

insert.table
way.

I am so confuuuused!

S.

Re: I still don't understand tables...

Posted: Saturday 19 February 2022 18:45
by jvdz
This is an explanation about LUA Arrays/Tables in general:
Basically you need to define a array (table) for each "level".
so taking it one step at a time to be able to do this:

Code: Select all

myTable[DzDeviceID].onActionUrl = myPremadeUrl
you need to define myTable as array:

Code: Select all

myTable = {}
This allows you to do:

Code: Select all

myTable["xyz"] = "test"    -- use this format when using a variable that contains "xyz"
-- or 
myTable.xyz = "test"      -- this needs to be an hardcoded xyz

In your case eaxch entry in the myTable array needs to be an Array of its own so you define it as such

Code: Select all

DzDeviceID = "xyz"
myTable[DzDeviceID] = {}
After that you can set it in either of these 2 ways:

Code: Select all

myTable[DzDeviceID]["onActionUrl"] = "testURL"
-- or 
myTable[DzDeviceID].onActionUrl = "testURL"
Any clearer this way? :)
Jos

Re: I still don't understand tables...

Posted: Friday 25 February 2022 17:08
by Sarcas
Thanks,

It helped me out a bit. Your examples & trial and error :) Not defining the arrays was one of the problems.