Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you fetch the last value of a table?

Hi, I've started working on lua recently, and I was trying to create a script that tells you how many items are in your inventory. I came across an issue; whenever I run the script it outputs as 1, 2.

inventory={"Sword","Arrow"}

function many()
	for k,v in pairs(inventory) do
		print (k)
	end
end

many()

I was wondering how to ONLY print out 2, or the last index number of the table. Thanks in advance.

2 answers

✓ Accepted answer

#What you can do I know this was answered twice already and this is also 19 hours old but there is a MUCH more simpler way to get the number of items inside of a table.


#Operators There are many types of operators that are distributed into 4 categories:

  • Logical
  • Relational
  • Arithmetic
  • Miscellaneous We're trying to find something that would return the length of something, so it wouldn't be Arithmetic or Logical and it can't be Relational either, so we'll look in Miscellaneous. The 2nd item on the list the ROBLOX Wiki gives us is the operator with the pound sign(#), the name of the operator/operation is "Length of Table"(Even though it'll work with the length of a string as well), this is perfect! ####Example of using "Length of Table"
local table = {1, nil, {"Red","String"}, true, workspace.BasePlate, BrickColor.new(1), CFrame.new()}
--These are all different values, also the operation counts tables inside of the ones being counted as a single object, excluding the things, or in this case strings, inside of the 2nd table.

print(#table)

7

It prints "7" because there are 7 things inside of the table. This is perfect for your inventory script.


#Final Product I know the explanation was long, but your modified script will be short, very short.

inventory={"Sword","Arrow"}

print(#inventory)

2



#Hope it helps!


##Extras Here's a quick function I made that will print the amount of things inside of any table:

function readtable(x)
	if type(x) == "function" then --If x is a table then...
		return #x
	end
end

readtable([Insert Table here]) --It will return the length of a table(Note, returning and printing aren't the same thing)

If the table is formatted as an array then the length of that table, #inventory, is always its last key. So to get its associated value, it's as simple as inventory[#inventory].

This discussion is preserved as it was. New answers, comments, and votes are closed.