pvklink wrote: Monday 21 October 2019 9:58
1. When i don't know the number of records in the table, is there a command to add it 'as the latest' (because you define a record-number) or do i read the table first and count the number of records?
2. the solution must have the option to store some names and values that belong together as a record like:
[{"ident": "aaaa", "var1": "1", "var2": "1"},{"ident": "zzzz", "var1": "2", "var2": "1"}]
and then add: ,{"ident": "bbbbb", "var1": "1", "var2": "7"}]
dzVents (=Lua) tables are key/value containers but can also be treated like an array.
t = {"a", "b", "c"} This is a syntax shortcut for t = {[1]="a", [2]="b", [3]="c"}
1.
If your table is build like an array with only consecutive numbers starting at 1, you can query the number of records in the table with #tablename
If the table is build with other keys or with gaps in the numbering or not starting with 1 then you will need to loop through the table the get the number of records. with something like the getTablePairsCount function in the next answer
2.
Code: Select all
local function getTablePairsCount(t)
local tableCounter = 0
for k,v in pairs(t) do
tableCounter = tableCounter + 1
end
return tableCounter
end
local function tableValuesToString(t,sep)
local myString = ''
local sep = sep or ',' -- default separator = ,
for k, v in pairs(t) do
if type(v) == 'string' then
myString = myString .. v .. sep
end
end
if myString ~= '' then return myString:gsub("[" .. sep .. "]*$",'') end -- return concatenated string after removing last separator
end
local rTable = {}
local record1 = '{"ident": "aaaa", "var1": "1", "var2": "1"}'
local record2 = '{"ident": "zzzz", "var1": "2", "var2": "1"}'
local record3 = '{"ident": "bbbbb", "var1": "1", "var2": "7"}'
rTable[1] = record1
rTable[#rTable + 1] = record2
rTable[#rTable + 1] = record3
print ('there are ' .. getTablePairsCount(rTable) .. ' records in the table') -- works on all tables
print ('there are ' .. #rTable .. ' records in the table') -- gives only a valid answer on pure array like tables
print ('[' .. table.concat(rTable,',') .. ']') -- table concat only concatenates the values within the pure array part of the table (with key 1,2,3,..)
rTable[0] = '{"ident": "00000", "var0"=": "0", "var00": "00"}'
rTable['negen'] = '{"ident": "999999", "var9"=": "9", "var99": "99"}'
print ('there are now ' .. getTablePairsCount(rTable) .. ' records in the table')
print ('there are now more then ' .. #rTable .. ' records in the table') -- #rTable does not give the count of all records now only the ones in the pure Array
print('\n\n')
print ('Values from pure array part of the table ==>> [' .. table.concat(rTable,',') .. ']') -- this does not print all the table values
print ('Values from complete table ==>> [' .. tableValuesToString(rTable,',') .. ']')
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>>
dzVents wiki