Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of table initialization in Lua

Tags:

lua

I know that there is no guarantee concerning table element order when iterating over all table elements using pairs(). The table elements could be returned in any order.

But what about initializing a table, e.g. consider the following code:

function func(x)
  print(x)
  return(x)
end   

t = {func(0), x = func(1), y = func(2), [0] = func(3), func(4), [1000] = func(5)}

The test shows that func() is called in the order the table elements are initialized but is this guaranteed? I don't seem to find anything about this in the Lua reference but I'm sure there must be some official explanation on this.

like image 435
Andreas Avatar asked Feb 22 '26 00:02

Andreas


1 Answers

The order of evaluation in table constructors and in function arguments is not defined to allow room for optimization by the compiler.

You shouldn't rely on the order of evaluation anyway.

This is not specific to Lua. Most languages don't specify order of evaluation in lists of expressions.

like image 103
lhf Avatar answered Feb 24 '26 02:02

lhf