简体   繁体   中英

Roblox Studio - Workspace.(My roblox ign).Name:8: attempt to index nil with 'DisplayName'

So I'm trying to choose a name out of a list and set the player's DisplayName to that.. This is a LocalScript in starterCharacterScripts.

local player = game.Players.LocalPlayer

print("Getting name of player ".. player.Name)
local Names = {<my names dont worry about em>}
local ChosenName = Names[math.random(1, #Names)]
print("Got name: " .. ChosenName)
local name = player.Name
game.Workspace.name.Humanoid.DisplayName = Names[math.random(1, #Names)]```

Why isn't ChosenName used in the last line, instead of Names[math.random(1, #Names)] ? This just chooses a random name for a second time, which may or may not match the name printed with "Got name: " .

But, to the matter at hand, what is the table referenced with game.Workspace.name.Humanoid.DisplayName ? The error seems to indicate that there is no DisplayName field, so I suspect that there is no Humanoid field yet added to the table.

> Names = {'Trillian', 'Ford', 'Arthur', 'Zaphod', 'Marvin'}
> ChosenName = Names[math.random(1, #Names)]

If the table OP code is working with already has a name field, then:

> game.Workspace.name.Humanoid = { DisplayName = ChosenName }

will work. If the table does not yet have a name field, then:

> game.Workspace.name = { Humanoid = { DisplayName = ChosenName }}

Either way, you should now have:

> game.Workspace.name.Humanoid.DisplayName
Marvin

Unless the game table does not yet have a Workspace field. The general principle here is that game.Workspace.name.Humanoid.DisplayName is syntactic sugar for game["Workspace"]["name"]["Humanoid"]["DisplayName"] . If the Workspace field is a table, then an attempt to access the name field is made; if the name field is a table, then an attempt to access the Humanoid field is made. If the Humanoid field has not yet been created, nil is returned, and ["DisplayName"] attempts to index nil , leading to the error.

Given a table like:

t = {}

You can create new fields one level deep with t.something = something , but you can't create nested table fields this way, eg t.something.else = something_else , because the first field something does not yet exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM