#!/usr/bin/lua -- Lua獲取tbale長度算法 --[[ Lua很少使用求長度的算法, 假設table的類型是數組,可以使用tbale.getn(table)或者# 但是也有風險,如果數組中有元素的值是nil,那么計算長度就會出錯 假設tbale是鍵值對,那么tbale.getn(table)或者#都無法使用,只能使用pairs()迭代器的方式 ]] local t1={1,2,3,4,5,6,7,8,9} local t2={a=1,b=2,c=3,d=4,e=5} -- 計算數組的長度 print("t1 length is ",table.getn(t1)) print("t1 length is ",#t1) -- 計算鍵值對的長度 local l = 0 for _,_ in pairs(t2) do l=l+1 end print("t2 length is ",l) -- 計算table的長度(Metatable) --[[ Lua 5.1版本不支持__len function len_event (op) if type(op) == "string" then return strlen(op) -- 原生的取字符串長度 elseif type(op) == "table" then return #op -- 原生的取 table 長度 else local h = metatable(op).__len if h then -- 調用操作數的處理器 return h(op) else -- 沒有處理器:缺省行為 error(···) end end end ]]