WhatIsProtocoll
WhatIsProtocoll

Reputation: 31

How do I access value in lua table?

I have following lua code that prints out the Mac Addresses of a device.

local sc = Command.Scan.create() 
local devices = sc:scan() 
local topicMac
local list = {}

for _,device in pairs(devices) do 
   print(device:getMACAddress())
   list[device] = device:getMACAddress()
end
  
topicMac = list[0]
print(topicMac)

Since there are several addresses and they are listed in a table, I would like to save only the first one into the local variable "topicMac". I tried reaching that first value by adding the first index (0 or 1) in the array.

Why do I get nil as return?

Upvotes: 1

Views: 388

Answers (2)

Maris
Maris

Reputation: 59

"First" and "Second" depends on what we have as keys. To check it just use print():

for k,d in pairs(devices) do 
  print(k,' = ',d:getMACAddress())
end

If keys are numbers, you can decide which is "first". If keys are strings, you are still able to make an algorithm to determine the first item in the table:

local the_first = "some_default_key"
for k,d in pairs(devices) do
  if k < the_first then   -- or use custom function: if isGreater(the_first,k) then
    the_first = k
  end
end
topicMac = devices[the_first]:getMACAddress()
print(topicMac)

If keys are objects or functions, you can't compare them directly. So you have to pick just any first item:

for _,d in pairs(devices) do 
  topicMac = d:getMACAddress()
  break
end
print(topicMac)

Upvotes: 0

Senor
Senor

Reputation: 36

The next keyword can be used as a variant function to retrieve the first index and value out of a table

local index, value = next(tab) -- returns the first index and value of a table

so in your case:

local _, topicMac = next(list)

Upvotes: 1

Related Questions