我有下面的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作为返回值?
发布于 2021-02-11 03:45:52
next关键字可用作变量函数,以便从表中检索表中的第一个索引和值
local index, value = next(tab) -- returns the first index and value of a table所以在你的例子中:
local _, topicMac = next(list)发布于 2021-02-11 13:11:39
“第一”和“第二”取决于我们有什么作为关键字。要检查它,只需使用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 -- or use custom function: 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)https://stackoverflow.com/questions/66143375
复制相似问题