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:
wait(3)
local player_table = game.Players:GetPlayers()
print(player_table)
player_table:getn()
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.
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.
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.
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.
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: