1
votes

I am working with Lua 5.0, what puzzles me is why the following code works:

for i in {first=1,second=2,third=3} do
    print(i)
end

It prints 'first', 'second', 'third'. However, according to the online programming in Lua for 5.0 "The first thing the for does is to evaluate the expressions after the in. These expressions should result in the three values kept by the for: the iterator function, the invariant state, and the initial value for the control variable."

In this case, the expression after the in is simply a table. It won't evaluate into (function, state, initial value), and any subsequent call would be a call to the table itself. But the above example works, why?

2

2 Answers

1
votes

The above mentioned for-loop is valid for version 4.0, see http://www.lua.org/manual/4.0/manual.html#4.4

A for statement like

   for index, value in exp do block end

is equivalent to the code:

   do
     local _t = exp
     local index, value = next(t, nil)
     while index do
       block
       index, value = next(t, index)
     end
   end

As shown, the "exp" after "in" could be a table. This is drastically different from the for syntax in 5.0 and onwards. However, my experiment shows that the 5.0 still respects this old style. This explains what I saw.

0
votes

In Lua 5.2 (the standard) this code produces the error

Runtime Error:
tst.lua:1: attempt to call a table value

So I don't know what you're doing, but either way, what you are doing is wrong.