Main Content

ourdog is Greyhound, Staffie and Ginger Cake

Archive - Originally posted on "The Horse's Mouth" - 2009-11-09 22:03:13 - Graham Ellis

It was the fact that the cake wrapper was on the bed, and not on the bedside table that was the clue that triggered me to realizing that something wasn't quite where I had left it. And examining the wrapper and finding it empty and clear, I realised that something else - the remaining slice of cake - was missing completely.

Which is why in my Lua coding example today I wrote that gypsy comprises Greyhound, Staffordshire Bull Terrier, and Ginger Cake.


gypsy = {"Greyhound","Staffordshire Bull Terrier","Ginger Cake"}

But that was yesterday and - well - she's our dog, so Lisa gave her some dogfood and the gravy she loves this morning:

ourdog = gypsy
ourdog[3] = "dogfood and gravy"


Now it appears that I have just changed the copy that I made of the table called "gypsy", doesn't it? And that if I were to print out the original table, it would still contain the Ginger Cake? Well - that turns out not to be the case:

print (table.concat(gypsy," and "))

gave me:

Greyhound and Staffordshire Bull Terrier and dogfood and gravy

and looking at the two tables:

print (gypsy, ourdog)

tells me that they're one and the same:

table: 0x9e34fd8 table: 0x9e34fd8

In Lua, when you copy a table, you're really just copying the reference - in other words you're giving it another name. And if you then alter it under one name, you'll alter it under the second name too.

As a second example, I asked one of my delegates today what he called his mother. "Mum" he replied. And I asked him what his father called his mother. "Margaret" he replied (not really, I'm protecting names). "Now - if your father poured a tin of pink paint over Margaret, would you say 'Mum, you're pink'" I asked. "Yes" he replied ...




Python behaves in the same way as Lua, as does version 5 of PHP ... version 4 of PHP and Perl both replicate the whole of a list / array, and you would still have seen the ginger cake when you printed out what Gypsy's made of! The Lua / Python / PHP5 behavior also has its equivalent in C with the copying of a pointer.