Having Trouble With getn() Function

Hello, I’m trying to learn how to use the getn() function on a table of players, but I’m getting an error.

Here’s the script:


local player_table = game.Players:GetPlayers()


The error is: attempt to call a nil value on the last Line.
I’ve tried adding a wait() in between retrieving the table and calling getn(), but it didn’t make a difference. I’ve tried assigning the results of getn() to a variable and then printing that, but to no avail.

The table prints just fine, so the variable definitely has a value. The first wait() is necessary so that the table actually has an entry (myself).

I would appreciate any help, thank you in advance.

use the hash operator instead


Thank you! This works. However, I’m curious as to why this is the preferred solution. The Docs didn’t mention this at all, and according to both the old and new Docs getn() is not deprecated.
Do you know the answer, or where I would find it?

The problem could just be how you’re using it. You’re trying to call getn as if it’s a method and the table is an OOP object, which it clearly isn’t (you’re basically trying to do player_table.getn(player_table)). table.getn(player_table) should still work fine.

1 Like

Couldn’t you just define it as an empty table first and then appended yourself using game.Players.PlayerAdded:Connect()?

This doesn’t work either. I should have mentioned that I tried this, apologies.

What’s the pros and cons of this method compared to getting the table as I need it?

But it is mentioned in the docs?

I meant that the hash thing isn’t mentioned in the docs for tables.

If you try to do that in a single statement, it won’t, because # is an operator, and it only works in expressions. Plus, evaluating that and discarding that is nonsensical because, well, you discard it.

Actually, here is a strange thing: The book “Programming in Lua” doesn’t list # as an operator. Still though, # only works in expressions.

I’m not sure what you’re referring to.

It’s mentioned in the official Lua docs. Since Roblox runs on Luau which is a fork of Lua, they automatically assume you know the basics of vanilla Lua, so those things are usually not covered.


Ah I see. I’m fairly new to scripting so finding the relevant documentation is still difficult. I appreciate your explanations.

I misinterpreted the text saying “This doesn’t work either” which probably was referring to table.getn and not #. I was referring to the fact that this alone:


has a syntax error.

1 Like