如何访问 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 作为回报?

解决方法

Future <DataSnapshot> getData()async{ List lists = []; await databaseReference.once().then((DataSnapshot snapshot) { Map < dynamic,dynamic > values = snapshot.value; values.forEach((key,values)async { await FirebaseDatabase.instance.reference().child("Users/" + values["UID"].toString() + "/Name").once().then((DataSnapshot snapshot) { lists.add(snapshot.value); print(snapshot.value); }); },); } ); print(lists); } 关键字可以用作变体函数来检索表中的第一个索引和值

next

所以在你的情况下:

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

“First”和“Second”取决于我们拥有的键。要检查它,只需使用 print():

import dash
import dash_bootstrap_components as dbc
from dash.dependencies import Input,Output,State
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import plotly.express as px


card_content1_1 = [
    dbc.CardHeader([dbc.Row([html.H5("SALES VOLUME TREND",className = "font-weight-bold text-success"),dbc.Button(
                       html.I(className="fa fa-window-maximize"),color="success",id="sales_maximize",className="ml-auto",# href="www.cogitaas.com"
                   )
                             ])]),dbc.CardBody(
        [dcc.Graph(
    id='sales_graph',figure={},style={'height':'30vh'}
    # className="mt-5"
            )])]


card_stacked_discount = [
    dbc.CardHeader([dbc.Row([html.H5("VOLUMES UNDER DIFFERENT DISCOUNT LEVELS",className="font-weight-bold text-info text-center"),color="info",id="discount_maximize",dbc.CardBody(
        [dcc.Dropdown(
                id = 'stacked_discount_dropdown',options =stacked_discount_options,value=stacked_discount_options[0].get('value'),style={'color':'black'},# multi=True
            ),dcc.Graph(
    id='stacked_discount_graph',style={'height':'30vh'}
            )])]
cards = html.Div(
        [
            dbc.Row(
                [
                    dbc.Col(dbc.Card(card_content1_1,outline=True,style={'height':'auto'}),width=8),],className="mb-4",),dbc.Row(
                [
                    dbc.Col(dbc.Card(card_stacked_discount,outline=True),dbc.Col(dbc.Card([
                        dbc.Row([
                            dbc.Col(dbc.Card(disc_sub_title,inverse=True)),]),html.Br(),dbc.Row([
                            dbc.Col(dbc.Card(disc_sub_card1,outline=True)),width=4)
                ],]
    )

tab1_content = dbc.Card(
    dbc.CardBody(
        [cards,]
    ),className="mt-3",)

tabs = dbc.Tabs(dbc.Tab(tab1_content,label="Data",label_style={'color':'blue'},tab_style={"margin-left":"auto"}),])

content = html.Div([
        html.Div([tabs]),id="page-content")

app.layout = html.Div([dcc.Location(id="url"),content])


@app.callback(
    dash.dependencies.Output('sales_graph','figure'),[dash.dependencies.Input('platform-dropdown','value'),dash.dependencies.Input('signature-dropdown',dash.dependencies.Input('franchise-dropdown',dash.dependencies.Input('sales_maximize','n_clicks'),dash.dependencies.Input('time-dropdown',])
def update_sales_graph(plat,sign,fran,maximize,time_per):
    print(str(time_per)+"Test")
    time_ax=[]
    if isinstance(time_per,str):
        time_ax.append(time_per)
        time_per=time_ax
    if (time_per==None) or ('Full Period' in (time_per)):
        dff = df[(df.Platform==plat) & (df.Signature==sign) & (df.Franchise==fran)]
    elif ('YTD' in time_per):
        dff = df[(df.Platform == plat) & (df.Signature == sign) & (df.Franchise == fran) & (df.year==2020)]
    else:
        dff = df[(df.Platform==plat) & (df.Signature==sign) & (df.Franchise==fran) & (df.Qtr_yr.isin(time_per))]

    fig = px.area(dff,x='Date',y='Qty_Orig',color_discrete_sequence=px.colors.qualitative.Dark2)
    fig.add_trace(go.Scatter(x=dff['Date'],y=dff['Outliers'],mode = 'markers',name='Outliers',line=dict(color='darkblue')))
    fig.add_trace(go.Scatter(x=dff['Date'],y=dff['bestfit'],name='Long Term Trend',line=dict(color='darkblue')))
    fig.update_layout(font_family="Rockwell",title={'text': fran + " Volume Trend",'y': 0.99,# 'x': 0.15,# 'xanchor': 'auto','yanchor': 'top'
                             },legend=dict(
                          orientation="h",# y=-.15,yanchor="bottom",x=0.5,xanchor="center"
                      ),yaxis_visible=False,yaxis_showticklabels=False,xaxis_title=None,margin=dict(l=0,r=0,t=0,b=0,pad=0),plot_bgcolor='White',paper_bgcolor='White',)
    fig.update_xaxes(showgrid=False,zeroline=True)
    fig.update_yaxes(showgrid=False,zeroline=True)
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    if 'maximize' in changed_id:
        fig.show()
    return fig


@app.callback(
    dash.dependencies.Output('stacked_discount_graph',dash.dependencies.Input('discount_maximize',dash.dependencies.Input('stacked_discount_dropdown',])
def stacked_discount(plat,sales_days,time_per):
    time_ax=[]
    if isinstance(time_per,str):
        time_ax.append(time_per)
        time_per=time_ax
    # else:
    #     time_per=list(time_per)

    if (time_per==None) or ('Full Period' in (time_per)):
        df_promo = df_promo_vol[(df_promo_vol.Platform==plat) & (df_promo_vol.Signature==sign) & (df_promo_vol.Franchise==fran)]
    elif ('YTD' in time_per):
        df_promo = df_promo_vol[(df_promo_vol.Platform == plat) & (df_promo_vol.Signature == sign) & (df_promo_vol.Franchise == fran) & (df_promo_vol.Year==2020)]
    else:
        df_promo = df_promo_vol[(df_promo_vol.Platform==plat) & (df_promo_vol.Signature==sign) & (df_promo_vol.Franchise==fran) & (df_promo_vol.Qtr_yr.isin(time_per))]

    color_discrete_map = {
        "0 - 10": "orange","10 - 15": "green","15 - 20": "blue","20 - 25": "goldenrod","25 - 30": "magenta","30 - 35": "red","35 - 40": "aqua","40 - 45": "violet","45 - 50": "brown","50 + ": "black"
    }

    category_orders = {'disc_range': ['0 - 10','10 - 15','15 - 20','20 - 25','25 - 30','30 - 35','35 - 40','40 - 45','45 - 50','50 + ']}

    if (sales_days == None) or (sales_days == 'sales_act'):
        fig = px.bar(df_promo,x='start',y='units_shipped',color='disc_range',color_discrete_map=color_discrete_map,category_orders=category_orders,)
    else:
        fig = px.bar(df_promo,y='Date',color="disc_range",)

    fig.update_layout(font_family="Rockwell",title={'text': fran + " Sales Decomposition",'x': 0.1,# yaxis_visible=False,t=30,b=30,zeroline=True)
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    if 'maximize' in changed_id:
        fig.show()
    return fig

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

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)