Live Chat!

Python vs Lua, data structure

          0 votos

June 28th, 2008 mysurface Posted in Developer, Lua, python | Hits: 15049 |

In python, we have various type of data structure, such as list, set, tuple, dictionary etc, but in Lua, we only have table. Table in Lua can be used as array, list, dictionary or object.

Let see how you we construct list from Lua table.

t = { 'a','b','c','d','e','f' }

To print out the whole list, we need general for in Lua:

for i,v in pairs(t) do
	print (i," = ", v)
end

Lua Results:

1        =      a
2        =      b
3        =      c
4        =      d
5        =      e
6        =      f

To create a list from python:

t = [ 'a','b','c','d','e','f' ]

Print out the list with the index:

for i in t:
    print t.index(i)," = ", i

Python Results:

0  =  a
1  =  b
2  =  c
3  =  d
4  =  e
5  =  f

Observed Lua and Python results, Lua list index start from 1, which means t[1] will be the first element in the list, where in python, index start from ZERO, so accessing first element in python with t[0].

Anyway, you can force Lua table start index from ZERO like this:

t = { [0]='a','b','c','d','e','f' }

But when you print out the result using for loop, it seems to be weird, the indexing does not start with ZERO but it will place ZERO at last slot.

1        =      b
2        =      c
3        =      d
4        =      e
5        =      f
0        =      a

I raise up this in Lua mailing list, Duncan replied, he provides a solution to cater this. He suggest creates another function based on ipairs like this:

local ipairsaux = ipairs({})
function ipairs2(t,i)
   return ipairsaux, t, (i or 1) - 1
end

t = { [0]='a','b','c','d','e','f' }
for i,v in ipairs2(t,0) do
   print (i," = ", v)
end

Lua’s table can be used as dictionary, lets see:

d = {a=1,b=2,c=3}
print(d['a'])
1

To further add in elements, you can do this:

d['q']=100
print(d['q'])
100

Let print out all the elements and value through for loop.

for e,v in pairs(d) do
	print(e,v)
end

a       1
q       100
c       3
b       2

Add another element and print them again:

d['j']=345
for e,v in pairs(d) do
	print(e,v)
end

q       100
c       3
b       2
j       345
a       1

It seems, the elements will be arrange by random.

For dictionary in python:

d= { 'a':1, 'b':2, 'c':3 }
for a in d:
    print a,d[a]

a 1
c 3
b 2

d['q']=200

for a in d:
    print a,d[a]

a 1
q 200
c 3
b 2

d['j']=20

for a in d:
    print a,d[a]

a 1
q 200
c 3
b 2
j 20

But amazing part of Lua’s dictionary can be access like this:

print(d.a)
1

Which it is identical to print(d['a']).

In python, you can’t do that, unless you define it as a class.

class D:
     pass
d=D()
d.a=1
d.b=2
d.c=3
print d.a
1

But object ‘d’ in python does not support for loop like dictionary. I might be wrong about this, because I see something like this in django.

Leave a Reply