lua 学习小记 table下标

来源:互联网 发布:2016年云计算市场份额 编辑:程序博客网 时间:2024/06/15 13:56

local a = {x = 10,"qqt",y = 20}

print(table.getn(a))      输出为1

t​able.getn返回值为最后一个值的下标,应该也要是数字。

a 中x=10,和y=20,下标分别为x,y,只有字符串 "qqt"的下标为1

对于数字下标的,要引用,使用a[1]

对于下标为字符的,可以用a["x"]或者​a.x

local a= {x=10,z,"qqt",y=20}

因为z未定义,为nil,table.getn(a)的返回值可能是指向任何一个是 nil 值的前一个位置的下标​,不确定,所以在table中,要避免出现nil的情况。

不能用#a或者table.getn(a) == 0 来判断table是否为空,因为local a = {x = 10,,y = 20}时,两者读出来的是0

可以用

function isTableEmpty(t)
    if t == nil or next(t) == nil then
        return true
    else
        return false
    end
end

对于用openresty mysql取出来的值

  • local select_sql = "select name,age from test"  
  • res, err, errno, sqlstate = db:query(select_sql)  
  • if not res then 

    ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)

return

 close_db(db)  

  • end
  •   

res的格式如下,

    { name = "wangxiaoer",age = "18"},

    { name = "zhanghong",age = "20"}​

}

第一条数据的下标为默认的1,​

print(table.getn(res))      --output   2

print(res[1].name)或print(res[1]["name"])   --output    wangxiaoer​

print(res[2].age)   --outpu​t   20

1 0
原创粉丝点击