1
votes

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?

2
Both using 0 or 1, results as "nil" on the console - WhatIsProtocoll
If you want to access a variable outside of its local context, don't declare it local. - Nicol Bolas
Even when not declaring it locally, return is "nil" - WhatIsProtocoll
Do you still need the whole list, or can you throw out everything except the first item? If you don't need the whole list, @Senor's answer is correct. - luther
There's a lot of missing information here: what does devices look like? what is the "first" MAC address to you, or do you just want any mac address form the list? why do you need a list in the first place if you just want the first address? - DarkWiiPlayer

2 Answers

1
votes

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)
0
votes

"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)