I am a newbie to Lua. trying out some tutorials. Its my understanding that in Lua a table is a key value storage with any permissible LUA types as keys other than nil. ipairs is a way to iterate over a table until the ipairs hit a nil key.
I tried the below with the above understanding. But the second ipairs loop is not printing anything. The below snippet prints the keys and values.
a ={}
for i=1,1000 do
a[i]=i
end
for i,data in ipairs(a)
do
print("key is:" .. i)
print("value is " .. data)
print("\n")
end
This one is not printing anything
b={}
b["a"]="a"
b["name"]="test"
b[10] ="b10"
b["@"]="@@"
for i,data in ipairs(b)
do
print("key is :" .. i)
print("data is :" .. data)
print("\n")
end
any idea as what is wrong?
Full code that I am trying out.
function work_with_table()
a = {}
for i=1,1000 do
a[i]=i
end
for i,data in ipairs(a)
do
print("key is:" .. i)
print("value is " .. data)
print("\n")
end
b={}
b["a"]="a"
b["name"]="test"
b[10] ="b10"
b["@"]="@@"
for i,data in ipairs(b)
do
print("key is :" .. i)
print("data is :" .. data)
print("\n")
end
end
work_with_table()
Edit 1:
I belive this block creates a pair? ("a",t["a"]) ("name", t["name"])
b={}
b["a"]="a"
b["name"]="test"
b[10] ="b10"
b["@"]="@@"
Edit 2:
use ipair when the table's index is integer based. Otherwise use pairs for generic key, value looping. Thanks all for the help...
ipairs
. – pmg