1

I'm discovering Lua with ComputerCraft (for Minecraft), and I need 2 functions :

  • the cardinal function #foo (for a given table named "foo")
  • popping out the last element from a table, for example : foo[#foo] = nil (is there something better ?)

What are the respective complexity of these functions ? I particularly need a O(1) way to pop the last element of a table.

Sorry for bad english, thanks in advance.

Wulfhartus
  • 13
  • 2

2 Answers2

2

ACcording to lua 5.4 reference (section 3.4.7), #t is logarithmic, not linear. It is explicitely written since lua 5.3, but probably it was also the case in lua 5.1 and 5.2 as well. It is also logarithmic in luajit.

But aS already said in the other answer above, you need to manually keep a record of the length if you want it to be O(1).

QuentinC
  • 12,311
  • 4
  • 24
  • 37
-1

#foo is O(n); it goes through the able until it finds nil, then returns the last index before it. Setting the last element to nil is indeed the "proper" way to pop, as nil is how the table length is defined, unless you're using getn/setn (which were deprecated in Lua 5.1 and removed in Lua 5.2).

The proper way to make it O(1) is to store the length elsewhere and update it every time something is added to or removed from the table.

Putnam
  • 704
  • 4
  • 14