Skip to content

Using Lua's length operator "#" #261

@lolleko

Description

@lolleko

Right now we are using # to translate Array.length.
However Lua's # behaves slightly different if a array containts "gaps"

local x = {1,2}
x[5] = 12
print(#x) -- prints 2 (executed in https://www.lua.org/cgi-bin/demo)
var arr = [1, 2];
arr[5] = 12;
console.log(arr.length); -- logs 6

Right now length is the only place where we use #,
but we were thinking about using # in forOf translation aswell #260.

Here are some possible solutions to the problem:

  • Leave it to the programmer not to have gaps in arrays and use # in transpiled lua.

  • Add a custom array type to lualib that patches __index and __newindex to keep track of the array/table length. (Probably wont work if arrays are passed from native lua)

  • Add an transpiler options called "safe mode" where we replace # with a custom function that gets the length by iterating with pairs. In unsafe mode just keep using #.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions