Anaminus / rbxmk

A tool for processing Roblox files.
MIT License
109 stars 11 forks source link

Using next as a iterator is broken in the custom lua VM #52

Open RaspyPiStyLiS opened 3 years ago

RaspyPiStyLiS commented 3 years ago

This script

local tbl = {1,2,3,4,5}
for i,v in next, tbl do
    print(i,v)
end

Will produce the following output

4       4
5       5

Expected output:

  1 1
  2 2
  3 3
  4 4
  5 5
Anaminus commented 3 years ago

When happens here is that the construction of tbl leaves 1, 2, 3, 4, and 5 on the stack. Then, to prepare for the generic-for operation, 1 is replaced by next, 2 is replaced by tbl, while 3, 4, and 5 are left alone. The problem is that the generic-for always looks for three values, which in this case will be next, tbl and 3, which turns into next(tbl, 3). To fix this, the compiler needs to ensure that, if a third expression is not specified, it is filled in with nil.

For now, you can work around this by specifying the nil explicitly:

local tbl = {1,2,3,4,5}
for i,v in next, tbl, nil do
    print(i,v)
end
--> 1   1
--> 2   2
--> 3   3
--> 4   4
--> 5   5