[Lua] 遍历table的时候,如果table中包含 有0为前缀的数字的字符串时,需要注意 - Gukie/learning GitHub Wiki

refer

具体坑

local function retrieve_number_from_table(str)
     local result_str_table = {};
     for item in string.gmatch(tostring(str), "([+-]?%d+%.?%d*)")
     do

        print("item:"..item..", type:"..type(item))
         table.insert(result_str_table, item);
     end
     return result_str_table
end

使用以上的function,进行输出

local user_id_list_str = "001,002,003";
local user_id_list = get_number_table(user_id_list_str);
print(unpack(user_id_list))
local matched_user_id;
for user_id in ipairs(user_id_list)
	do
    print("user_id:"..user_id..",type:"..type(user_id))
    ...
end

会发现,输出的是:

001 002 003
user_id:1,type:number
user_id:2,type:number
user_id:3,type:number

可是我们就是想要它是一个 字符串 "001" 而非 数字"1"

折腾了半天,发现在user_id前面加上一个 游标,可以解决这个问题...

for k,user_id in ipairs(user_id_list)
	do
    print("user_id:"..user_id..",type:"..type(user_id))
    ...
end

for的用法解释

The generic for loop allows you to traverse all values returned by an iterator function. We have already seen examples of the generic for:

-- print all values of array `a'
for i,v in ipairs(a) do print(v) end

For each step in that code, i gets an index, while v gets the value associated with that index. A similar example shows how we traverse all keys of a table:

-- print all keys of table `t' 这里只是输出key,而非value
for k in pairs(t) do print(k) end