lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi, list

Here are the related code snippets(which are contained in a file named
as test.lua):
local mt = {}
local Set = {}

function Set.new (l) -- 2nd version
local set = {}
setmetatable(set, mt)
for _, v in ipairs(l) do set[v] = true end
return set
end


function Set.union (a, b)
local res = Set.new{}
print(#res)
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res
end

-- presents a set as a string
function Set.tostring (set)
local l = {} -- list to put all elements from the set
for e in pairs(set) do
l[#l + 1] = tostring(e)
end
return "{" .. table.concat(l, ", ") .. "}"
end

s1 = Set.new{10, 20, 30, 50}
s2 = Set.new{30, 1}
print(s1[10],s1[20],s1[30],s1[50])
print(s1[1],s1[2],s1[3])
print(#s1)

print("\noutput is ok below")
--output is ok
for k, v in pairs(s1) do
print(k, v)
end


for k, v in pairs(s2) do
print(k, v)
end

print("\noutput is strange below, why?")
--output is strange, why
for k, v in ipairs(s1) do
print(k, v)         --output nothing
end

print("---------------")
for k, v in ipairs(s2) do
print(k, v)          --only outputs the last elment
end

Here is the outputs while run the script(i.e. lua test.lua) on Lua-5.3.5 :

true    true    true    true
nil     nil     nil
0

output is ok below
20      true
50      true
10      true
30      true
1       true
30      true

output is strange below, why?
---------------
1       true

Why does the output of "for in pairs" is right whereas the output of
"for in ipairs" is wrong?

I have thought and thought about it, but I am still confused now.
I would be grateful to have some help with help with this question.

Best regards
Sunshilong