Search code examples
lualua-tablefirst-class-functionszerobrane

Different behavior when assigning a function to a variable or a table


I have got a different behavior between a table and a simple variable assignation with a function. This difference does not exist when assigning a number for instance.

-- works fine
arrNum={1234}
Num=arrNum[1] -- Num=1234
arrNum[2]=arrNum[1] -- arrNum={1234,1234}

--does not work fine
arrFunc={function(x) return 10*x end}
func=arrFunc[1] -- func=function(x) return 10*x end
arrFunc[2]=arrFunc[1] -- arrFunc={function(x) return 10*x end,nil}

func is function(x) return 10*x end but : I get arrFunc={function(x) return 10*x end,nil} instead of arrFunc={function(x) return 10*x end,function(x) return 10*x end}

I don't understand this difference when for me func and arrFunc[2] are just the same "box" for receiving data, including first-class functions.

May be a clue (I do not catch) : in the console, after the last line is executed, I have the following info :

arrFunc

{function() --[[..skipped..]] end --[[function: 0x90d7d0]], nil --[[ref]]} --[[table: 0x93afc0]] --[[incomplete output with shared/self-references skipped]]

Solution

  • In fact the problem has nothing to do with lua but seems to be an artefact of the IDE.

    It seems the displays of my ZeroBrane console and on-site comments are erroneous. When I execute the program, everything runs just fine.