lua表格中如何访问值?

我有以下的 lua 代码,可以打印出设备的 Mac 地址。

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)

由于有多个地址,它们被列在一个表格中,我想仅将第一个地址保存到本地变量"topicMac"中。我尝试通过在数组中添加第一个索引(0或1)来访问第一个值。

为什么返回值为nil

点赞
用户15185749
用户15185749

next 关键字可以作为一种变体函数,用于检索出一个表中的第一个索引和值。

local index, value = next(tab) -- 返回一个表的第一个索引和值

所以在你的情况下:

local _, topicMac = next(list)
2021-02-10 19:45:52
用户10964422
用户10964422

"First" 和 "Second" 取决于我们有什么样的键。为了检查它,只需使用 print():

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

如果键是数字,您可以决定哪一个是“第一”。如果键是字符串,则仍然可以制定算法来确定表中的第一项:

local the_first = "some_default_key"
for k,d in pairs(devices) do
  if k < the_first then   -- 或使用自定义函数:if isGreater(the_first,k) then
    the_first = k
  end
end
topicMac = devices[the_first]:getMACAddress()
print(topicMac)

如果键是对象或函数,则无法直接比较它们。因此,您必须选择任何一个第一项:

for _,d in pairs(devices) do
  topicMac = d:getMACAddress()
  break
end
print(topicMac)
2021-02-11 05:11:38