Andreas
Andreas

Reputation: 10077

Order of table initialization in 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.

Upvotes: 3

Views: 138

Answers (1)

lhf
lhf

Reputation: 72342

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.

Upvotes: 5

Related Questions