length operator for the arrays

  • From: Alexander <malandrinus2009@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 6 May 2016 03:45:44 -0400

Hello,

I noticed a difference in Lua behavior in LuaJIT 2.x from that in LuaJIT 1.x.
The difference is in the length operator for the arrays. To explain the 
difference,
it is better to show the code example.

local t = {1, nil, 2}
local len = #t

In LuaJIT 1.x the len will be 3, and in the LuaJIT 2.x it will be 1.
This also affects the inserting into arrays. With the same t array as in the 
code above:

table.insert(t, 3)
will insert 3 at the index 4 in the LuaJIT 1.x and at the index 2 in the LuaJIT 
2.x.

This new behavior is very undesirable. One particular situation where it makes 
quite a difference
is the code, is where I want to analyze a variable list of arguments. Before, I 
could use a code like this:

function fun(...)
    local args = {...}
    for i=1,#args do
        local arg = args[i]
        -- do something
    end
end

in a situation when I will call this function like this

fun(1, nil, 2)

the given approach worked fine. With the new behavior this approach does not 
work, and I don't see
any reasonably simple way to get an actual number of arguments passed to the 
function.

I am trying to transfer to LuaJIT 2 a big project with a hundreds of Lua files. 
This change can potentially break
a lot of code where people relied on the old behavior.

By the way. I checked the generic Lua versions from 5.1 to 5.3, and it seems 
that that "old" behavior was never changed
and still remains the way how the length operator works.


Is there any way to get the old/generic behavior of the length operator? Macro 
switch? Some easy fix?

Thanks in advance.

Best regards,
Alexander


Other related posts: